使用python从重定向的stdin中读取文件


问题内容

我正在尝试读取通过命令行重定向到stdin的文本文件的内容,并在接收方必须将其重新组合回其原始格式时通过Internet发送它。

例如:

$ python test.py < file.txt

我试图读取该文件,并使用以下受链接启发的代码将其组合回去:

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一个接一个),这个解决方案就可以工作,如果我确实有,我的循环会中断并且文件读取结束。如何从stdin读取直到我到达了已重定向文件的<>?


问题答案:

您为什么还要查看数据:

result = sys.stdin.read()