popen
我在基于终端的进程间通信中遇到了一些类似的问题,使用(et al.)似乎无法解决。我最终pty
通过阅读pexpect的源代码学习了如何使用,其中包含如何(以及为什么的评论)pty
跳过必要的箍的示例。
当然,根据您的需要,您也可以只使用pexpect!
这是我在自己的项目中使用的内容。请注意,我没有检查子进程是否终止;该脚本旨在作为管理长时间运行的 Java 进程的守护进程运行,因此我不必处理状态代码。但是,希望这将为您提供所需的大部分内容。
import os
import pty
import select
import termios
child_pid, child_fd = pty.fork()
if not child_pid: # child process
os.execv("/path/to/command", ["command", "arg1", "arg2"])
# disable echo
attr = termios.tcgetattr(child_fd)
attr[3] = attr[3] & ~termios.ECHO
termios.tcsetattr(child_fd, termios.TCSANOW, attr)
while True:
# check whether child terminal has output to read
ready, _, _ = select.select([child_fd], [], [])
if child_fd in ready:
output = []
try:
while True:
s = os.read(child_fd, 1)
# EOF or EOL
if not s or s == "\n":
break
# don't store carriage returns (no universal line endings)
if not s == "\r":
output.append(s)
except OSError: # this signals EOF on some platforms
pass
if output.find("Enter password:") > -1:
os.write(child_fd, "password")