我尝试使用子进程在main_script.py中运行test_script.py。 test_script.py是一个siple sum程序,main_script.py应该用2个参数调用它,并捕获输出。这是代码:
test_script.py
a = int(input())
b = int(input())
print(a+b)
main_script.py
import subprocess
subprocess.check_output(['python', 'test_script.py', 2,3])
这是我得到的错误:
Traceback (most recent call last):
File "C:/Users/John/Desktop/main_script.py", line 2, in <module>
subprocess.check_output(['python', 'test_script.py', 2,3])
File "C:\Python34\lib\subprocess.py", line 607, in check_output
with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
File "C:\Python34\lib\subprocess.py", line 858, in __init__
restore_signals, start_new_session)
File "C:\Python34\lib\subprocess.py", line 1085, in _execute_child
args = list2cmdline(args)
File "C:\Python34\lib\subprocess.py", line 663, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: argument of type 'int' is not iterable
答案 0 :(得分:0)
参数的所有部分都必须是一个字符串。请改为:
subprocess.check_output(['python', 'test_script.py', "2", "3"])
如果此命令无法运行,您将获得异常。抓住它并看到输出:
try:
subprocess.check_output(['python', 'test_script.py', "2", "3"], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print e.output
您的第二个脚本将失败,因为它期望来自stdin的输入,而您的主脚本正在发送2
和3
作为参数。调查sys.argv
答案 1 :(得分:0)
https://docs.python.org/3/library/subprocess.html#subprocess.check_output
import subprocess
subprocess.check_output("python test_script.py", stderr=subprocess.STDOUT, shell=True)