关闭通过 pty.openpty() 创建的 PseudoTTY

Close a PseudoTTY created via pty.openpty()

我正在使用 pty.openpty() 来欺骗根据 isatty() 改变其行为的子进程,大致如下:

import pty
import subprocess

master, slave = pty.openpty()
with subprocess.Popen(cmd, stdin=slave) as process:
    stdout, stderr = process.communicate()

然而,在多次执行此操作后(作为自动化测试的一部分),我得到:

E           OSError: [Errno 24] Too many open files

../../miniconda/envs/aclimatise-test/lib/python3.7/subprocess.py:1393: OSError

E       OSError: out of pty devices
../../miniconda/envs/aclimatise-test/lib/python3.7/pty.py:59: OSError

出于某种原因,pty 模块文档没有告诉我如何或何时关闭我正在分配的伪 TTY。我应该如何以及何时这样做?还是我使用 pty 的方式完全错误?

如果有帮助,我正在使用 Python 3.6+,使用 Linux(我认为这是使用此模块的要求)。

可以使用os.close关闭master和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.

尝试在 subprocess.Popen

中设置 close_fds=True
subprocess.Popen(
  # ...
  close_fds=True,
)