我正在使用 Python 2.6 开发 GUI 前端,通常它相当简单:您使用 subprocess.call()
或 subprocess.Popen()
发出命令并等待它完成或对错误使用react。如果你有一个程序停止并等待用户交互,你会怎么做?例如,程序可能会停止并询问用户 ID 和密码或如何处理错误?
c:\> parrot
Military Macaw - OK
Sun Conure - OK
African Grey - OK
Norwegian Blue - Customer complaint!
(r) he's Resting, (h) [Hit cage] he moved, (p) he's Pining for the fjords
到目前为止,我所阅读的所有内容都告诉您如何仅在 完成后读取程序的所有输出,而不是在程序仍在运行时如何处理输出。我无法安装新模块(这是针对 LiveCD 的),而且我将多次处理用户输入。
最佳答案
查看 subprocess手动的。您可以使用 subprocess
选项来重定向您的进程的 stdin
、stdout
和 stderr
重新呼唤你自己的。
from subprocess import Popen, PIPE, STDOUT
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print grep_stdout
您还可以逐行与流程交互。鉴于这是 prog.py
:
import sys
print 'what is your name?'
sys.stdout.flush()
name = raw_input()
print 'your name is ' + name
sys.stdout.flush()
您可以通过以下方式与它逐行交互:
>>> from subprocess import Popen, PIPE, STDOUT
>>> p = Popen(['python', 'prog.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
>>> p.stdout.readline().rstrip()
'what is your name'
>>> p.communicate('mike')[0].rstrip()
'your name is mike'
编辑:在 python3 中,它需要是 'mike'.encode()
。
关于Python子进程和用户交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14457303/