我正在 Python 3.5 中做一个 GIT 钩子。 python 脚本调用 Bash 脚本,该脚本使用以下命令读取用户的输入read
命令。
bash 脚本本身可以工作,在直接调用 python 脚本时也可以,但是当 GIT 运行用 Python 编写的钩子时,它不会按预期工作,因为没有请求用户输入。
重击脚本:
#!/usr/bin/env bash
echo -n "Question? [Y/n]: "
read REPLY
GIT 挂钩(Python 脚本):
#!/usr/bin/env python3
from subprocess import Popen, PIPE
proc = Popen('/path/to/myscript.sh', shell=True, stderr=PIPE, stdout=PIPE)
stdout_raw, stderr_raw= proc.communicate()
当我执行Python脚本时,Bash的read
似乎没有等待输入,我只得到:
b'\nQuestion? [Y/n]: \n'
如何让 bash 脚本从 Python 调用时读取输入?
事实证明,这个问题与 Python 无关:如果 GIT 钩子调用了 bash 脚本,它也无法请求输入。
给出了我找到的解决方案here https://stackoverflow.com/a/10015707/220949.
基本上,解决方案是将以下内容添加到 bash 脚本中之前read
:
# Allows us to read user input below, assigns stdin to keyboard
exec < /dev/tty
就我而言,我还必须像这样调用 bash 进程Popen(mybashscript)
代替Popen(mybashscript, shell=True, stderr=PIPE, stdout=PIPE))
,因此脚本可以自由输出到 STDOUT,而不会在 PIPE 中捕获。
或者,我没有修改 bash 脚本,而是在 Python 中使用:
sys.stdin = open("/dev/tty", "r")
proc = Popen(h, stdin=sys.stdin)
上述链接的评论中也建议了这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)