How do I iterate over all lines of files passed on the command line?

后端 未结 5 1834
温柔的废话
温柔的废话 2021-02-04 02:54

I usually do this in Perl:

whatever.pl

while(<>) {
    #do whatever;
}

then cat foo.txt | whatever.pl

Now, I

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-04 03:26

    I hate to beat a dead horse, but may I suggest using a pure function?

    import sys
    
    def main(stdin):
      for line in stdin:
        print("You said: " + line.strip())
    
    if __name__ == "__main__":
      main(sys.stdin)
    

    This approach is nice because main is dependent purely on its input and you can unit test it with anything that obeys the line-delimited input stream paradigm.

提交回复
热议问题