Python子进程和用户交互

41

我正在使用Python 2.6开发GUI前端,通常情况下很简单:你使用subprocess.call()或者subprocess.Popen()来执行命令并等待其完成或响应错误。那么如果你有一个程序需要停止并等待用户交互怎么办?例如,程序可能会停止并要求用户输入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而准备的),而且我将不止一次地处理用户输入。


你的意思是让一个子进程像命令行客户端一样工作吗? - stanleyerror
相关:Python subprocess communicate中的多个输入和输出(也请阅读评论)。 - jfs
1个回答

41

查看subprocess手册。使用subprocess,您可以选择重定向正在调用的进程的stdinstdoutstderr到您自己的流中。

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()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接