如果你不想做超出你的例子在命令行上任何花哨的东西,你将不得不标准输入重定向到终端的第一件事就是你的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
来调用它。