Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a File from redirected stdin with python

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?

like image 259
user3717551 Avatar asked Dec 05 '14 14:12

user3717551


2 Answers

Why are you even looking at the data:

result = sys.stdin.read()
like image 172
William Pursell Avatar answered Sep 21 '22 00:09

William Pursell


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
like image 26
chepner Avatar answered Sep 18 '22 00:09

chepner