Python subprocess and user interaction

纵然是瞬间 提交于 2019-11-26 20:24:43

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'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!