Read a File from redirected stdin with python

痞子三分冷 提交于 2020-01-21 07:29:08

问题


I am trying to read the content of a text file that was redirected stdin via the command line, and send it by the Internet when the receiver has to assemble it back to it's original form.

For instance:

$ python test.py < file.txt

I have tried to read the file and to assemble it back with the following code inspired by 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!"

But this solution works as long as I DON'T have an empty row( two '\n' one after another) in my file,if i do have, my loop breaks and the File reading ends.How can I read from stdin till i reach <> of the file that was redirected?


回答1:


Why are you even looking at the data:

result = sys.stdin.read()



回答2:


Instead of breaking, you just want to continue to the next line. The iterator will stop automatically when it reaches the end of the file.

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



回答3:


line.strip() is removing the trailing newline from the read line.

If you want that newline then you shouldn't need to do that I don't think (does your output file have the input newlines)?

That if stripped bit is looking for a blank line and was, in the original, the termination characteristic of the loop.

That isn't your termination marker though. You don't want to stop there. So don't.

The loop will finish on its own when sys.stdin reaches the end of the input (EOF).

Drop line.strip() drop if not stripped: break replace result = result + stripped with result = result + line and then write that to the file to get a simple (though likely expensive) cp script.

There are likely more efficient ways to read all the lines from standard input if you want to do something with them though (depending on your goal).



来源:https://stackoverflow.com/questions/27318022/read-a-file-from-redirected-stdin-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!