如何从stdin运行Python源代码并读取stdin的内容?

7

我有一个Python源文件,看起来像这样:

import sys
x = sys.stdin.read()
print(x)

我希望通过将源文件传递给Python的标准输入来调用该源文件: python < source.py
在读取source.py之后,我希望Python程序开始从stdin读取(如上所示)。这是否可能?看起来解释器在获得EOF之前不会处理source.py,但是如果接收到EOF,则sys.stdin.read()将无法正常工作。
2个回答

8

使用另一个FD。

import os

with os.fdopen(3, 'r') as fp:
  for line in fp:
    print line,

...

$ python < source.py 3< input.txt

2

如果您不想在命令行中执行任何高级操作,只需按照您的示例将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

我相信这样做可以达到你想要的效果。
编辑:
我错了。这对于你的用例来说是失败的。你需要一些方法将当前的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

我想补充一点,我认为最明智的方法是完全避免这个问题-不要将脚本重定向到Python的标准输入,而是使用python source.py直接调用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接