Reading file from redirected stdin using python

I am trying to read the contents of a text file redirected by stdin via the command line and send it over the Internet when the receiver needs to collect it back to its original form.

For instance:

$ python test.py < file.txt 

I tried reading the file and compiling it with the following code inspired by the 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 until I have an empty line (two "\ n" one after another) in my file, if I have it, my loop break and reading the file. How can I read from stdin to i to the <> file that has been redirected?

+5
source share
3 answers

Why do you even look at the data:

 result = sys.stdin.read() 
+5
source

Instead of breaking, you just want to continue to go to the next line. The iterator will automatically stop 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
source

line.strip() removes the line.strip() newline from the read line.

If you need this new line, you do not need to do this, I don’t think (does your output file have new lines)?

This if stripped bit searches for an empty string and was in the original a characteristic of loop completion.

This is not your graduation marker. You do not want to stop there. So do not do this.

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

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

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

+2
source

Source: https://habr.com/ru/post/1208434/


All Articles