python 如何遍历命令行上传递的所有文件行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/715277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:43:29  来源:igfitidea点击:

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

pythonstdin

提问by Tg.

I usually do this in Perl:

我通常在 Perl 中这样做:

whatever.pl

随便.pl

while(<>) {
    #do whatever;
}

then cat foo.txt | whatever.pl

然后 cat foo.txt | whatever.pl

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

现在,我想在 Python 中做到这一点。我试过了,sys.stdin但我不知道该怎么做,就像我在 Perl 中所做的那样。我怎样才能读取输入?

回答by Don Werve

Try this:

试试这个:

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

回答by Mark Roddy

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

回答by David Z

Something like this:

像这样的东西:

import sys

for line in sys.stdin:
    # whatever

回答by Can Berk Güder

import sys

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

回答by Vishal Kotcherlakota

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 完全依赖于它的输入,您可以使用任何符合行分隔输入流范式的内容对其进行单元测试。