我正在编写一个Python脚本,必须调用第二个包含输入字段的python脚本。 在Linux命令窗口中调用第二个脚本的常规方法是:
python 2ndpythonscript.py input_variable output_variable
现在,我想从第一个脚本中调用此脚本。我该怎么做?提前谢谢。
答案 0 :(得分:2)
使用subprocess
模块,例如:
import subprocess
retcode = subprocess.call(['python', '2ndpythonscript.py', 'input_variable', 'output_variable'])
模块中有不同的专用函数,如果只需要返回代码,只需要输出,stdout / stderr都可以在自定义管道中重定向,等等。
答案 1 :(得分:1)
使用subprocess.check_call,任何非零退出状态都会引发错误:
from subprocess import check_call
check_call(["python", "2ndpythonscript.py" ,"input_variable" ,"output_variable"])
如果您想获得输出,请检查check_output:
from subprocess import check_output
out = check_output(["python", "2ndpythonscript.py" ,"input_variable" ,"output_variable"])