【问题标题】:Read input from user and store it to a variable using subprocess从用户读取输入并使用子进程将其存储到变量中
【发布时间】: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


【解决方案1】:

你正在输入一个shell命令(readecho是shell内置的,&amp;&amp;是shell语法),因此你需要shell=True。这是一个单一的 shell 命令,所以你不要使用split。在这种情况下,python中命令周围的括号不起作用:

import sys
import subprocess
sys.stdin = open('/dev/tty', 'r')

cmd = 'read userinput && echo "$userinput"'
confirmation = subprocess.check_output(cmd, stdin=sys.stdin, shell=True).rstrip()

print'****', confirmation

给予:

$ python gash.py
hello
**** hello

【讨论】:

  • 嗨@cdarke,感谢您的回答。但出于安全考虑,我严格需要shell=False;你知道我可以用什么方法来完成我想要的任务吗?
  • 哪些安全注意事项也不适用于 python 脚本?底线是,不使用 shell 就无法执行 shell 命令。
  • 还有安全注意事项,如here中所述
猜你喜欢
  • 2013-01-25
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 2012-01-05
  • 2017-04-17
  • 1970-01-01
相关资源
最近更新 更多