python - GIT 钩子(Hook) -> Python -> Bash : How to read user input?

标签 python linux git bash githooks

我在 Python 3.5 中做一个 GIT 钩子(Hook)。 python 脚本调用 Bash 脚本,该脚本使用 read 命令读取用户的输入。

bash 脚本本身可以工作,当直接调用 python 脚本时也是如此,但是当 GIT 运行用 Python 编写的钩子(Hook)时,它不会按预期工作,因为没有请求用户输入。

bash 脚本:

#!/usr/bin/env bash

echo -n "Question? [Y/n]: "
read REPLY

GIT 钩子(Hook)(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 钩子(Hook)调用 bash 脚本,它也无法请求输入。

我找到的解决方案是here .

基本上,解决方案是在 read 之前将以下内容添加到 bash 脚本中:

# Allows us to read user input below, assigns stdin to keyboard
exec < /dev/tty

在我的例子中,我还不得不像 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)

上述链接的评论中也有建议。

关于python - GIT 钩子(Hook) -> Python -> Bash : How to read user input?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009781/

相关文章:

python - Python 字典的处理成本有多高?

c - "__gmon_start__"符号是什么?

linux - bashrc 在运行 bash 命令之前不会加载

linux - 在 Qt 包装器类中使用 libudev 监控 eth0

git - git pull --rebase --ff-only 做什么?

git - 在不破坏文件历史记录的情况下 merge 两个 Git 存储库

python - 读取文件最后一行的函数?

python - 如何在 Pandas 查询中引用分层列?

python - math.exp() 定义在 python 源代码的哪个位置?

git 直接添加子模块哈希