subprocess的输入输出处理

来源:互联网 发布:java中的sleep 编辑:程序博客网 时间:2024/05/22 05:24

最近在用Python处理一些应用程序的交互,subprocess的Popen可以实现应用的stdin和stdout交互,但在实际使用过程中,Popen的stdin并不是经常work。

下面是Mark别人的代码,在Python2.7.x下测试通过。

1,Case1 简单输出

#test1.py  import sys  line = sys.stdin.readline()  print 'test',linesys.stdout.flush()

#run1.pyfrom subprocess import *proc =Popen('test1.py', stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=True)string = 'say hi\n'proc.stdin.write(string)line = proc.stdout.readline()print(line)proc.stdout.flush()

在命令行下运行 python run1.py,得到打印如下:

> test say hi


2, Case 2 连续输入输出

# test2.pyimport syswhile True:    line = sys.stdin.readline()    if not line:        break    sys.stdout.write(line)    sys.stdout.flush()

# run2.pyimport sysfrom subprocess import *proc = Popen('test2.py',stdin=PIPE,stdout=PIPE,stderr=STDOUT,shell=True)line = raw_input()while line != 'q':    proc.stdin.write(line + '\n')    proc.stdin.flush()    output = proc.stdout.readline()    sys.stdout.write(output)    sys.stdout.flush()    line = raw_input()

在命令行下,运行 python run2.py,然后可不停的输入,得到相同的输出,直至输入字符‘q'退出程序。


以上两个是用于学习的Case,在某个实际应用中发现,获取Popen的stdin后,第一次write成功,再次write时就不起作用了,但应用程序依旧运行,未得到预期效果,纳闷了~

Mark一下,希望尔后能解释。

原创粉丝点击