I'm using pty.openpty()
to fool a subprocess that changes its behaviour based on isatty()
, vaguely like this:
import pty
import subprocess
master, slave = pty.openpty()
with subprocess.Popen(cmd, stdin=slave) as process:
stdout, stderr = process.communicate()
However, after doing this many many times (as part of automated testing), I get:
E OSError: [Errno 24] Too many open files
../../miniconda/envs/aclimatise-test/lib/python3.7/subprocess.py:1393: OSError
and
E OSError: out of pty devices
../../miniconda/envs/aclimatise-test/lib/python3.7/pty.py:59: OSError
For some reason the pty
module documentation doesn't tell me how or when to close the pseudoTTYs that I'm allocating. How and when should I do so? Or am I using pty
in entirely the wrong way?
If it helps, I'm on Python 3.6+, using Linux (which I think is a requirement for using this module).
You can use os.close to close master and slave.
os.close(fd) Close file descriptor fd.
Note This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To close a “file object” returned by the built-in function open() or by popen() or fdopen(), use its close() method.