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

自闭症网瘾萝莉.ら 提交于 2019-12-03 08:40:45

问题


I usually do this in Perl:

whatever.pl

while(<>) {
    #do whatever;
}

then cat foo.txt | whatever.pl

Now, I want to do this in Python. I tried sys.stdin but I have no idea how to do as I have done in Perl. How can I read the input?


回答1:


Try this:

import fileinput
for line in fileinput.input():
    process(line)



回答2:


import sys
def main():
    for line in sys.stdin:
        print line
if __name__=='__main__':
    sys.exit(main())



回答3:


Something like this:

import sys

for line in sys.stdin:
    # whatever



回答4:


import sys

for line in sys.stdin:
    # do stuff w/line



回答5:


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.



来源:https://stackoverflow.com/questions/715277/how-do-i-iterate-over-all-lines-of-files-passed-on-the-command-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!