如何使用子流程获取 return 值?
How can I get return values with subprocess?
我正在编写一个 Python 脚本,它使用子进程调用 python 并处理多个函数,例如以下简化代码。 (当然,下面的脚本是行不通的。)
如何从每个函数中获取 return 值?请帮帮我。
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()
如果您以非交互方式打开 python,那么它会等到它在 运行 脚本之前读取所有标准输入,因此您的示例将无法运行。如果您编写命令然后在阅读之前关闭标准输入,如下所示,您可以获得结果。
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
我正在编写一个 Python 脚本,它使用子进程调用 python 并处理多个函数,例如以下简化代码。 (当然,下面的脚本是行不通的。)
如何从每个函数中获取 return 值?请帮帮我。
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()
如果您以非交互方式打开 python,那么它会等到它在 运行 脚本之前读取所有标准输入,因此您的示例将无法运行。如果您编写命令然后在阅读之前关闭标准输入,如下所示,您可以获得结果。
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