简体   繁体   English

如何迭代命令行上传递的所有文件行?

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

I usually do this in Perl: 我通常在Perl中这样做:

whatever.pl whatever.pl

while(<>) {
    #do whatever;
}

then cat foo.txt | whatever.pl 那么cat foo.txt | whatever.pl cat foo.txt | whatever.pl

Now, I want to do this in Python. 现在,我想用Python做到这一点。 I tried sys.stdin but I have no idea how to do as I have done in Perl. 我试过sys.stdin但我不知道怎么做,就像我在Perl中做的那样。 How can I read the input? 我该如何阅读输入?

Try this: 试试这个:

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

Something like this: 像这样的东西:

import sys

for line in sys.stdin:
    # whatever
import sys

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

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. 这种方法很好,因为main完全依赖于它的输入,你可以用符合行划分的输入流范例的任何东西对它进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM