我正在使用Python 3.5中的GIT钩子。 python脚本调用一个Bash脚本,该脚本使用read
命令读取用户的输入。
当直接调用python脚本时,bash脚本本身也可以工作,但是当GIT运行用Python编写的钩子时,它不能按预期工作,因为用户没有请求用户输入。
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调用时读取输入?
答案 0 :(得分:1)
添加
print(stdout_raw)
print(stderr_raw)
显示
b''
b'/bin/sh: myscript.sh: command not found\n'
这里。添加./到myscript.sh为READ一次python工作可以找到脚本。 CWD =#&39;'在Popen也可以工作。
答案 1 :(得分:0)
事实证明问题与Python无关:如果GIT钩子调用了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))
一样调用bash过程,因此脚本可以自由输出到STDOUT而不会被PIPE捕获。
或者,我没有修改bash脚本,而是在Python中使用:
sys.stdin = open("/dev/tty", "r")
proc = Popen(h, stdin=sys.stdin)
也在上述链接的评论中提出。
答案 2 :(得分:0)
这是在没有从python中调用bash脚本的情况下对我有用的。这是arod的答案的修改版本。
import subprocess
import sys
sys.stdin = open("/dev/tty", "r")
user_input = subprocess.check_output("read -p \"Please give your input: \" userinput && echo \"$userinput\"", shell=True, stdin=sys.stdin).rstrip()
print(user_input)