Read a File from redirected stdin with python

后端 未结 3 891
孤街浪徒
孤街浪徒 2021-01-13 10:33

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

相关标签:
3条回答
  • 2021-01-13 10:52

    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
    
    0 讨论(0)
  • 2021-01-13 11:01

    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).

    0 讨论(0)
  • 2021-01-13 11:07

    Why are you even looking at the data:

    result = sys.stdin.read()
    
    0 讨论(0)
提交回复
热议问题