How do I write a unix filter in python?

前端 未结 4 690
梦毁少年i
梦毁少年i 2021-01-04 08:44

I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let\'s say

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 09:00

    Use the -u switch for the python interpreter to make all reads and writes unbuffered. Similar to setting $| = true; in Perl. Then proceed as you would, reading a line modifying it and then printing it. sys.stdout.flush() not required.

    #!/path/to/python -u
    
    import sys
    
    for line in sys.stdin:
        process_line(line)
    

提交回复
热议问题