Reputation: 79
Before I start just wants to tell you all that i'm a beginner in python :)
I'm running a python script via git bash while committing code changes(using git hook[commit-message]) and I wants to read some user input from git bash terminal and the same has to be sent to my python script where i'll validate that, I tried many options that are available in python modules like getpass, subprocess, msvcrt and others but nothing worked for me. So could someone guide me or show me the code how to achieve this?
Below is the one of the sample code I have used,
import sys
sys.stderr.write("Enter> ")
s=input("")
print(s)
and the output is below, actually the terminal control(stdin) doesn't wait to get user input instead it simply ended.
Referred below links but nothing worked out for me :( bash script which executes a python script which prompts user GIT hook -> Python -> Bash: How to read user input?
Upvotes: 0
Views: 3642
Reputation: 1985
I suggest you read
user-input via bash
terminal then pass it as a parameter to your Python script.
This is going to be your Python script file:
import sys
def main():
if len(sys.argv) == 1:
print(1) # break commiting proccess
return
username = sys.argv[1]
password = sys.argv[2]
# stuff to do before commiting (git hook)
if username == 'peyman' and password == '2020':
print(0) # print 0 if everything works fine and you want to continue commiting
else:
print(1) # print non-zero if something goes bad and you want to break commiting proccess
if __name__ == "__main__":
main()
and this is going to be your pre-commit
file in the .git/hook/π folder:
#!/bin/bash
echo "Username:"
exec < /dev/tty
read Username
echo "Password:"
read Password
x=$(python main.py $Username $Password)
exit $x
As you know, if pre-commit
exit with 0
, the committing process will execute, and if pre-commit
return non-zero, committing will abort. So if you print(0)
in your Python script, the output set to exit
command like this: exit 0
As you said all the process done in the Python script file
Upvotes: 3
Reputation: 899
I donβt think you want stderr. Try this:
s = input("Enter> ")
print(s)
Update: that doesn't seem to work for you. The other way to read input in Python is as follows:
>>> x = sys.stdin.readlines(1)
testing
>>> x
['testing\n']
>>> x[0].rstrip('\n') # isolate the input
'testing'
However, this is probably a problem with the environment the script is being run in. Could you provide more detail in the question, so that we can reproduce your issue? Otherwise, the answer you find seems to solve your issue https://stackoverflow.com/a/46016718/13676619.
Upvotes: 2