[英]Close a PseudoTTY created via pty.openpty()
I'm using pty.openpty()
to fool a subprocess that changes its behaviour based on isatty()
, vaguely like this:我正在使用
pty.openpty()
来愚弄一个基于isatty()
改变其行为的子进程,大概是这样的:
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.出于某种原因,
pty
模块文档没有告诉我如何或何时关闭我正在分配的伪 TTY。 How and when should I do so?我应该如何以及何时这样做? Or am I using
pty
in entirely the wrong way?还是我以完全错误的方式使用
pty
?
If it helps, I'm on Python 3.6+, using Linux (which I think is a requirement for using this module).如果有帮助,我在 Python 3.6+,使用 Linux(我认为这是使用此模块的要求)。
You can use os.close to close master and slave.您可以使用 os.close 关闭主从。
os.close(fd) Close file descriptor fd.
os.close(fd) 关闭文件描述符 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().
注意此 function 用于低级 I/O,并且必须应用于 os.open() 或 pipe() 返回的文件描述符。 To close a “file object” returned by the built-in function open() or by popen() or fdopen(), use its close() method.
要关闭由内置 function open() 或 popen() 或 fdopen() 返回的“文件对象”,请使用其 close() 方法。
try setting close_fds=True
in subprocess.Popen
尝试在
subprocess.Popen
中设置close_fds=True
subprocess.Popen(
# ...
close_fds=True,
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.