我与基于终端的进程间通信,这似乎不是可解使用popen
一些类似的问题(等人)中。我结束了学习如何通过阅读pexpect源,其中包含(和为什么评论)获得pty
通过必要跳火圈的例子如何使用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")
这是一堆很好的代码来挖掘(但相信我,我打算)。是否有机会在此发布重要摘要? – user648855 2011-03-07 22:26:44
我会,但在工作时无法使用该机器。如果您可以等待大约五个小时(对不起),我很乐意在回家时发布一些示例。 – 2011-03-07 22:31:48
对不起!忘了发布此更早。 – 2011-03-08 07:09:13