簡體   English   中英

如何在傳遞給 Python 腳本的 Git-Bash 終端中讀取用戶輸入

[英]How can I read user Input in Git-Bash terminal which passes to a Python Script

在我開始之前只想告訴你我是 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'我會驗證這一點,我嘗試了 python 模塊中可用的許多選項,例如 getpass、subprocess、msvcrt 等,但對我沒有任何作用。 那么有人可以指導我或向我展示如何實現這一目標的代碼嗎?

以下是我使用的示例代碼之一,

import sys
sys.stderr.write("Enter> ")
s=input("")
print(s)

output 在下面,實際上終端控件(stdin)並沒有等待用戶輸入,而是簡單地結束了。 Git Bash 終端的輸出

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?

我不認為你想要標准錯誤。 嘗試這個:

s = input("Enter> ")
print(s)

更新:這似乎對你不起作用。 在 Python 中讀取輸入的另一種方法如下:

>>> x = sys.stdin.readlines(1)
testing
>>> x
['testing\n']
>>> x[0].rstrip('\n')  # isolate the input
'testing'

但是,這可能是腳本運行環境的問題。您能否在問題中提供更多詳細信息,以便我們重現您的問題? 否則,您找到的答案似乎可以解決您的問題https://stackoverflow.com/a/46016718/13676619

我建議您通過bash終端read用戶輸入,然后將其作為參數傳遞給您的python 腳本

這將是您的python腳本文件:

import sys

def main():
    if len(sys.argv) == 1:
        print(1) # break commiting proccess 
        return
    username = sys.argv[1]
    password = sys.argv[2]
 
    # kinda stuff to do before commiting (git hook) 

    if username == 'peyman' and password == '2020':
        print(0) # print 0 if everything works fine and you wanna continue commiting
    else:
        print(1) # print non-zero if something goes bad and you wanna break commiting proccess

if __name__ == "__main__":
    main()

這將是您在 .git/hook/ 文件夾中的pre-commit文件:

#!/bin/bash
echo "Username:"
exec < /dev/tty
read Username
echo "Password:"
read Password
x=$(python main.py $Username $Password)
exit $x

如您所知,如果pre-commit0退出,則提交過程將執行,如果pre-commit返回非零,則提交將中止。 因此,如果您在python 腳本print(0) ,則 output 設置為exit命令,如下所示: exit 0

正如你所說的 python 腳本文件中完成的所有過程

測試了一下,可以了~
快樂編碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM