Python子进程和用户交互 [英] Python subprocess and user interaction

查看:591
本文介绍了Python子进程和用户交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python 2.6的GUI前端工作,通常很简单:你使用subprocess.call()或subprocess.Popen()发出命令,并等待它完成或反应一个错误。如果你有一个程序停止并等待用户交互,你该怎么办?例如,程序可能会停止并要求用户输入ID和密码或如何处理错误?

  c:\>鹦鹉
军事金刚鹦鹉 - OK
Sun Conure - OK
非洲灰色 - OK
挪威蓝 - 客户投诉!
(r)他是休息,(h)[打击笼]他搬来了,(p)他是为峡湾Pining

到目前为止,我阅读的每一个都告诉你如何在程序完成后读取程序的所有输出,而不是在程序仍在运行时如何处理输出。我不能安装新的模块(这是一个LiveCD),我会多次处理用户输入。

解决方案

p>查看子流程手册。您可以使用 subprocess 的选项重定向 stdin stdout stderr

 从子流程导入Popen,PIPE,STDOUT 

p = Popen(['grep','f '],stdout = PIPE,stdin = PIPE,stderr = STDOUT)

grep_stdout = p.communicate(input ='one\\\
two\\\
three\\\
four\\\
five\\\
six\ n')[0]
print grep_stdout

线。给定为 prog.py

  import sys 
print'你叫什么名字?'
sys.stdout.flush()
name = raw_input()
print'你的名字是'+ 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()
'你叫什么名字'
>>> p.communicate('mike')[0] .rstrip()
'your name is mike'


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?

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 AFTER it'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.

解决方案

Check out the subprocess manual. You have options with subprocess to be able to redirect the stdin, stdout, and stderr of the process you're calling to your own.

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:

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'

这篇关于Python子进程和用户交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆