使用单个python脚本,我希望一个程序的输出被另一个程序中的第二个程序捕获和使用。我尝试使用子进程在单个python脚本中运行这两个程序:
ORA-00932: inconsistent datatypes: expected a Java type at argument position 2 to which some Oracle value can be converted got something else
答案 0 :(得分:1)
听起来你想要shell管道https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline
p1 = Popen(["python", "prog1.py"], stdout=PIPE)
p2 = Popen(["python", "prog2.py"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
output = p2.communicate()[0]
答案 1 :(得分:1)
如果prog2
仅接受输入作为文件名,即,如果您需要模拟bash进程替换:prog2 <(prog1 input_1.txt)
然后为了避免将prog1
子进程的输出写入磁盘,您可以如果您的操作系统支持,请使用/dev/fd/N
特殊文件名:
#!/usr/bin/env python2
import sys
from subprocess import Popen, PIPE
prog1 = Popen([sys.executable, "prog1.py", "input_1.txt"], stdout=PIPE)
with prog1.stdout:
cmd2 = [sys.executable, "prog2.py", "/dev/fd/%d" % prog1.stdout.fileno()]
prog2 = Popen(cmd2, stdout=PIPE)
output = prog2.communicate()[0]
statuses = [prog1.wait(), prog2.returncode]
您应该检查prog2
是否支持特殊文件名'-'
来读取stdin的输入,即模拟管道:prog1 input_1.txt | prog2 -
:
#!/usr/bin/env python
import sys
from subprocess import Popen, PIPE
prog2 = Popen([sys.executable, "prog2.py", "-"], stdin=PIPE, stdout=PIPE)
prog1 = Popen([sys.executable, "prog1.py", "input_1.txt"], stdout=prog2.stdin)
output = prog2.communicate()[0]
statuses = [prog1.wait(), prog2.returncode]
或者(更好)导入模块而不是将它们作为子进程运行并运行相应的函数,必要时使用多处理。见Call python script with input with in a python script using subprocess