Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GIT hook -> Python -> Bash: How to read user input?

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.

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 script:

#!/usr/bin/env bash

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

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()

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'

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

like image 547
arod Avatar asked Aug 29 '26 07:08

arod


1 Answers

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.

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

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.

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.

like image 83
arod Avatar answered Aug 31 '26 21:08

arod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!