【问题标题】:Read a File from redirected stdin with python使用 python 从重定向的标准输入读取文件
【发布时间】:2014-12-05 14:24:47
【问题描述】:

我正在尝试读取通过命令行重定向标准输入的文本文件的内容,并在接收者必须将其组装回原始形式时通过 Internet 发送。

例如:

$ python test.py < file.txt

我已尝试读取该文件并使用以下受link 启发的代码将其组装回来:

for line in sys.stdin:
  stripped = line.strip()
  if not stripped: break
  result = result + stripped

print "File is beeing copied"
file = open("testResult.txt", "w")
file.write(result)
file.close()
print "File copying is complete!"

但是只要我的文件中没有空行(两个 '\n' 一个接一个),这个解决方案就可以工作,如果我有,我的循环会中断并且文件读取结束。我该如何阅读从标准输入直到我到达被重定向的文件的?

【问题讨论】:

  • file.write(sys.stdin.read())
  • 对于像我这样愚蠢的人,在你进入 SO 兔子洞之前,请确保你的终端与 .txt 文件位于同一目录中(否则它将运行一个空文件)。

标签: python shell stdin


【解决方案1】:

你为什么还要看数据:

result = sys.stdin.read()

【讨论】:

  • 谢谢!这正是我所需要的:)
【解决方案2】:

您只想continue 到下一行,而不是中断。迭代器将在到达文件末尾时自动停止。

import sys
result = ""
for line in sys.stdin:
    stripped = line.strip()
    if not stripped:
        continue
    result += stripped

【讨论】:

    【解决方案3】:

    line.strip() 正在从读取行中删除尾随换行符。

    如果你想要那个换行符,那么我认为你不需要这样做(你的输出文件是否有输入换行符)?

    if stripped 位正在寻找一个空行,并且在原来的情况下是循环的终止特征。

    但这不是你的终止标记。你不想停在那里。所以不要。

    sys.stdin 到达输入的末尾 (EOF) 时,循环将自行结束。

    删除 line.strip() 删除 if not stripped: breakresult = result + stripped 替换为 result = result + line,然后将其写入文件以获得简单(虽然可能很昂贵)cp 脚本。

    如果您想对标准输入中的所有行进行某些操作(取决于您的目标),可能有更有效的方法来读取标准输入中的所有行。

    【讨论】:

    • 是的,你是对的,我不需要剥离(因为它会改变它读取的文本,这不是我的目标)。事实上,“William Pursell”提出了一种更“有效的方法”。
    猜你喜欢
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 2015-07-05
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多