Python子进程和用户交互
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14457303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python subprocess and user interaction
提问by Dave Brunker
I'm working on a GUI front end in Python 2.6 and usually it's fairly simple: you use subprocess.call()or subprocess.Popen()to issue the command and wait for it to finish or react to an error. What do you do if you have a program that stops and waits for user interaction? For example, the program might stop and ask the user for an ID and password or how to handle an error?
我正在 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
So far everything I've read tells you how to read all output from a program only afterit's finished, not how to deal with output while the program is still running. I can't install new modules (this is for a LiveCD) and I'll be dealing with user input more than once.
到目前为止,我读过的所有内容都告诉您如何仅在程序完成后读取程序的所有输出,而不是在程序仍在运行时如何处理输出。我无法安装新模块(这是针对 LiveCD 的),而且我将不止一次处理用户输入。
采纳答案by Mike
Check out the subprocessmanual. You have options with subprocessto be able to redirect the stdin, stdout, and stderrof the process you're calling to your own.
查看子流程手册。你有选择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
You can also interact with a process line by line. Given this as prog.py:
您还可以逐行与流程交互。鉴于此为prog.py:
import sys
print 'what is your name?'
sys.stdout.flush()
name = raw_input()
print 'your name is ' + name
sys.stdout.flush()
You can interact with it line by line via:
您可以通过以下方式逐行与其交互:
>>> 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'
EDIT: In python3, it needs to be 'mike'.encode().
编辑:在 python3 中,它需要是'mike'.encode().

