我有一个Python源文件,看起来像这样:
import sys
x = sys.stdin.read()
print(x)
我希望通过将源文件传递给Python的标准输入来调用该源文件: python < source.py
在读取
source.py
之后,我希望Python程序开始从stdin读取(如上所示)。这是否可能?看起来解释器在获得EOF之前不会处理source.py
,但是如果接收到EOF,则sys.stdin.read()
将无法正常工作。我有一个Python源文件,看起来像这样:
import sys
x = sys.stdin.read()
print(x)
source.py
之后,我希望Python程序开始从stdin读取(如上所示)。这是否可能?看起来解释器在获得EOF之前不会处理source.py
,但是如果接收到EOF,则sys.stdin.read()
将无法正常工作。使用另一个FD。
import os
with os.fdopen(3, 'r') as fp:
for line in fp:
print line,
...
$ python < source.py 3< input.txt
如果您不想在命令行中执行任何高级操作,只需按照您的示例将stdin重定向到终端即可。您可以通过从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
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
我想补充一点,我认为最明智的方法是完全避免这个问题-不要将脚本重定向到Python的标准输入,而是使用python source.py
直接调用它。