如何通过子流程获取返回值?

时间:2016-05-10 13:24:47

标签: python python-2.7 subprocess

我正在编写一个Python脚本,它使用子进程调用python并处理几个函数,如下面的简化代码。 (当然,以下脚本不起作用。)

如何从每个函数中获取返回值?请帮帮我。

import subprocess

p = subprocess.Popen("python", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("1+3\n")
print p.stdout.read()
p.stdin.write("2+4\n")
print p.stdout.read()

1 个答案:

答案 0 :(得分:1)

如果你以非交互方式打开python,那么它会等到它在运行脚本之前读取所有stdin,所以你的例子将不起作用。如果您编写命令然后在读取之前关闭stdin,则可以得到结果。

import subprocess

p = subprocess.Popen("python", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("print 1+3\n")
p.stdin.write("print 2+4\n")
p.stdin.close()
print p.stdout.read()

或者,使用“-i”强制python进入交互模式:

import subprocess

p = subprocess.Popen(["python", "-i"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("1+3\n")
print p.stdout.readline()
p.stdin.write("2+4\n")
print p.stdout.readline()
p.stdin.write("4+6\n")
print p.stdout.readline()
p.stdin.close()

这会产生:

Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> >>> 4

>>> 6

>>> 10
相关问题