子进程标准输入

Subprocess stdin input

我正在尝试将参数传递给我的 test_script.py,但出现以下错误。我知道这不是最好的方法,但它是唯一可行的方法,因为我不知道 test_script.py 中有哪些函数。如何将参数作为 stdin 输入传递?

test_script.py

a = int(input())
b = int(input())

print(a+b)

main_script.py

try:
  subprocess.check_output(['python', 'test_script.py', "2", "3"], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
  print(e.output)

错误

b'Traceback (most recent call last):\r\n File "test_script.py", line 1, in <module>\r\n a = int(input())\r\nEOFError: EOF when reading a line\r\n'

不确定您要做什么,但这是一个有效的示例:

import sys

# print('Number of arguments:', len(sys.argv), 'arguments.')
# print('Argument List:', str(sys.argv))

# print(sys.argv[1])
# print(sys.argv[2])

a = int(sys.argv[1])
b = int(sys.argv[2])

print(a+b)

还有你的main_script.py

import subprocess

try:

  out = subprocess.check_output(['python', 'test_script.py', "2", "3"], stderr=subprocess.STDOUT)
  print(out)

except subprocess.CalledProcessError as e:
  print(e.output)

那是行不通的,test_script.py 需要键盘输入而不是参数。

如果你想main_script.py传递参数给test_script.py你必须修改test_script.py 下面的代码应该可以解决问题

import sys

args = sys.argv[1:]
for arg in args:
    print arg

否则你可以检查 argparse https://docs.python.org/2/library/argparse.html

如果不想用argv,不过是奇数,考虑Popen和operating/communicating上stdin/stdout

from subprocess import Popen, PIPE, STDOUT

p = Popen(['python', 'test_script.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

p_stdout = p.communicate(input=b'1\n2\n')[0]
# python 2
# p_stdout = p.communicate(input='1\n2\n')[0]
print(p_stdout.decode('utf-8').strip())
# python2
# print(p_stdout)

来自 SO Python subprocess and user interaction 的参考。

还有关于 https://pymotw.com/2/subprocess/

的更多信息