from subprocess import Popen, PIPE, STDOUT
first = Popen(['myexe.exe'], stdout=PIPE, stderr=STDOUT, stdin=PIPE)
while first.poll() is None:
data = first.stdout.read()
if b'press enter to' in data:
first.stdin.write(b'\n')
first.stdin.close()
first.stdout.close()
这个管道
stdin
同样,不要忘记关闭打开的文件句柄(stdin和stdout在某种意义上也是文件句柄)。在还要避免
shell=True
如果可能的话,我经常自己使用它,但是best practices say you shouldn't。在这里我假设python3,}假设字节数据作为输入和输出。在
stdin
和{first.poll()
将轮询exe的退出代码,如果没有给定,则表示它仍在运行。在其他一些提示
一件乏味的事是把论点传给波本,一件简单的事是:
^{pr2}$它保留空格分隔的输入,并在其周围加引号,例如
python myscript.py debug "pass this parameter somewhere"
将导致来自sys.argv
的三个参数,['myscript.py', 'debug', 'pass this parameter somewhere']
-在将来使用Popen
时可能会有用另一个好的方法是在读取
stdout
之前检查它是否有输出,否则它可能会挂起应用程序。为此,您可以使用select。或者,您可以使用pexpect,这通常与SSH一起使用,因为它位于应用程序之外的另一个用户空间中,当它请求输入时,您需要手动分叉exe并使用
os.read()
从特定的pid中读取,或者使用pexpect
。在相关问题 更多 >
编程相关推荐