如果你不想做超出你的例子在命令行上任何花哨的東西,你將不得不標準輸入重定向到終端的第一件事就是你的Python腳本。你可以通過在Python中調用命令tty
並獲取你的tty的路徑,然後將sys.stdin改爲這個來實現。
import sys, os
tty_path = os.popen('tty', 'r').read().strip() # Read output of "tty" command
sys.stdin = open(tty_path, 'r') # Open the terminal for reading and set stdin to it
我相信應該做你想做的。
編輯:
我誤會了。這對你的用例會失敗。您需要一些將當前TTY路徑傳遞給腳本的方法。試試這個:
import sys, os
tty_path = os.environ['TTY']
sys.stdin = open(tty_path, 'r') # Open the terminal for reading and set stdin to it
但你必須調用腳本稍有不同:
TTY=`tty` python < source.py
我要補充一點,我覺得sanest方式迴避這個問題完全-將不會重定向腳本到python的標準輸入,並用python source.py
來調用它。