【问题标题】:Read input from redirected stdin with python使用 python 从重定向的标准输入读取输入
【发布时间】:2012-03-24 05:59:37
【问题描述】:

我有这个循环从标准输入读取行,直到输入换行符,但是,这只适用于输入输入。如何让程序通过命令行从重定向的标准输入读取行?

例如:

$ python graph.py < input.input

这是我必须从输入中读取行的循环:

while 1:
     line = sys.stdin.readline()
     if line == '\n':
         break
     try:
       lines.append(line.strip())
     except:
       pass

【问题讨论】:

  • 程序挂在循环的第二行并且不会退出,除非我用键盘打断它。
  • 您确定您的文件以 '\n' 行结尾吗?您可能在这里遇到了无限循环。您的文件很可能以 '' 行结尾。

标签: python shell stdin


【解决方案1】:

考虑以下选项

import sys
sys.stdin = open("input.txt", "r")

【讨论】:

    【解决方案2】:

    正如其他人所提到的,您的条件line == '\n' 可能永远不会成立。正确的解决方案是使用如下循环:

    for line in sys.stdin:
      stripped = line.strip()
      if not stripped: break
      lines.append(stripped)
    

    【讨论】:

      【解决方案3】:

      ETA:根据您遇到无限循环的评论,您可能只是文件末尾没有空行。


      使用pipe 字符:

      input.input | python graph.py
      

      如果input.input 实际上是文件而不是流,请使用cat 从中创建流:

      cat input.input | python graph.py
      

      【讨论】:

      • 这应该有什么帮助??
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多