【发布时间】:2019-06-11 11:01:53
【问题描述】:
我正在尝试通过在 python2.7 中使用subprocess.check_output 来读取用户的输入并将其存储在一个变量中。但是当我尝试运行它时,它会显示错误OSError: [Errno 2] No such file or directory。另外需要注意的是,出于安全考虑,我非常想使用shell=False。
我已经尝试过subprocess.Popen,但它也不起作用。
我尝试使用sys.stdin = open('/dev/tty', 'r') 和stdin=subprocess.PIPE,但给出与上述相同的错误。
>>> import sys
>>> import subprocess
>>> sys.stdin = open('/dev/tty', 'r')
>>> cmd = ('read userinput && echo "$userinput"')
>>> confirmation = subprocess.check_output(cmd.split(), stdin=sys.stdin).rstrip()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 567, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
预期的结果是它应该要求用户输入并将其存储到confirmation 变量中
【问题讨论】:
-
您没有使用
input()有什么特别的原因吗? -
实际上我在
pre_push_hook.py文件中使用它,这是一个 git 钩子。因此,当脚本运行时,它会被复制到.git/hooks目录并在 git 控制台中运行。所以当我尝试使用input()(或raw_input())时,它给出了'EOFError'。实际上,我只是尝试将 `sys.stdin.flush()和sys.stdin = open('/dev/tty', 'r')放入其中,并且 `raw_input()' 按预期工作
标签: python bash python-2.7 subprocess