Python 子进程检查输出不工作

Python subprocess check output not working

我正在尝试 运行 我的 test_script.py 在 main_script.py 中使用子进程。 test_script.py 是一个简单的求和程序,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

参数的所有部分都必须是一个字符串。请改为执行以下操作:

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

您的第二个脚本将失败,因为它需要来自标准输入的输入,而您的主脚本正在发送 23 作为参数。调查 sys.argv

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)