GIT挂钩-> Python-> Bash:如何阅读用户输入? [英] GIT hook -> Python -> Bash: How to read user input?

查看:83
本文介绍了GIT挂钩-> Python-> Bash:如何阅读用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python 3.5做一个GIT钩子. python脚本调用Bash脚本,该脚本使用read命令从用户读取输入.

I'm doing a GIT hook in Python 3.5. The python script calls a Bash script that that reads input from the user using read command.

bash脚本本身也可以工作,直接调用python脚本时也可以,但是当GIT运行用Python编写的钩子时,它不能按预期方式工作,因为用户没有要求用户输入.

The bash script by itself works, also when calling directly the python script, but when GIT runs the hook written in Python, it doesn't work as expected because no user input is requested from the user.

Bash脚本:

#!/usr/bin/env bash

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

GIT挂钩(Python脚本):

GIT Hook (Python script):

#!/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似乎没有在等待输入,我只能得到:

When I execute the Python script, Bash's read does not seem to be waiting for an input, and I only get:

b'\nQuestion? [Y/n]: \n'

从Python调用时,如何让bash脚本读取输入?

How to let the bash script read input when being called from Python?

推荐答案

事实证明,该问题与Python无关:如果GIT挂钩调用了bash脚本,它也不会要求输入.

It turns out the problem had nothing to do with Python: if the GIT hook called a bash script it also failed to ask for input.

此处给出了我找到的解决方案.

The solution I found is given here.

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

Basically, the solution is to add the following to the bash script before the read:

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

就我而言,我还必须像Popen(mybashscript)而不是Popen(mybashscript, shell=True, stderr=PIPE, stdout=PIPE))那样调用bash进程,因此脚本可以自由输出到STDOUT,而不会在PIPE中捕获.

In my case, I also had to call the bash process simply like Popen(mybashscript) instead of Popen(mybashscript, shell=True, stderr=PIPE, stdout=PIPE)), so the script can freely output to STDOUT and not get captured in a PIPE.

或者,我没有修改bash脚本,而是在Python中使用了

Alternatively, I didn't modify the bash script and instead used in Python:

sys.stdin = open("/dev/tty", "r")
proc = Popen(h, stdin=sys.stdin)

在上述链接的注释中也有建议.

which is also suggested in the comments of the aforementioned link.

这篇关于GIT挂钩-&gt; Python-> Bash:如何阅读用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆