子流程标准输入

诺比

我正在尝试将参数传递给我的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'
石英

如果不想使用argv,但是很奇怪,请考虑在标准输入/标准输出上进行Popen和操作/通信

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子流程和用户交互的参考

以及有关https://pymotw.com/2/subprocess/的更多信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章