Python子进程和用户交互

标签 python command-line subprocess popen frontend

我正在使用 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 选项来重定向您的进程的 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()

关于Python子进程和用户交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14457303/

相关文章:

Python:如何在每次输出而不是终止时获取子进程的输出?

python - 在 matplotlib pyplot 中,如何按类别对条形图中的条形进行分组?

python - 什么时候应该从ABC继承?

python - 重命名 dask 数据框中的列

c# CommandLine.Parser - 使用接受 Action<ParserSettings> 的构造函数

linux - BASH - 找不到 xargs 命令

xml_grep 从元素中获取属性

python - 有没有办法通过添加附加列来取消分组数据框

python - 使用python中的子进程运行以utf-8编码的Windows批处理文件

Python 子进程将输出返回为 stderr