【问题标题】:Subprocess stdin input [duplicate]子进程标准输入[重复]
【发布时间】:2015-11-28 20:25:49
【问题描述】:

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

test_script.py

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

print(a+b)

ma​​in_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'

【问题讨论】:

  • main_script 中,您将数字作为参数传递,但在test_script 中,您试图从stdin 中读取它们
  • 是的,我知道,但我不知道如何解决
  • 你到底想做什么?
  • 一个测试其他脚本的脚本,您输入输入数据并读取输出,如果您知道正确的输出,您可以查看该脚本是否正常工作
  • 骗子几乎涵盖了你需要的一切

标签: python subprocess stdin


【解决方案1】:

如果不想使用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 subprocess and user interaction 的参考。

还有更多关于https://pymotw.com/2/subprocess/的信息

【讨论】:

  • 我收到错误:p_stdout = p.communicate(input='1\n2\n')[0] File "C:\Python34\lib\subprocess.py", line 959, in communicate stdout, stderr = self._communicate(input, endtime, timeout) File "C:\Python34\lib\subprocess.py", line 1195, in _communicate self.stdin.write(input) TypeError: 'str' does not support the buffer interface
  • 编辑为兼容python3
【解决方案2】:

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

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)

【讨论】:

  • 这可行,但它使用sys.argv,有什么办法可以使用input(),或者将input()更改为sys.argv
【解决方案3】:

这会起作用,test_script.py 期望键盘输入而不是参数。

如果你希望 ma​​in_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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    相关资源
    最近更新 更多