Pythonic方式跟踪stdin中的行号

时间:2018-05-14 01:43:57

标签: python stdin line-count

我正在编写一个python脚本,它从stdin获取输入,并希望跟踪stdin输入的行号。

我可以自己创建一个计数器,但我感觉python会自动跟踪行号,因此这会浪费计算量。我还没有找到如何获得/打印这个数字。

我已经阅读并尝试了.tell()方法,但它跟踪字符(或字节)而不是行。当输入来自stdin时,它似乎也失败了。它抛出IOError: [Errno 29] Illegal seek

我的测试脚本" pythonTest.py"看起来像:

import sys
with sys.stdin as file:
    for line in file:
        print(line.rstrip())
        # Neat way to print the line number

执行上面的那个(就像现在一样):

$ echo 'asdf
asdf
asdf
asdf' | python pythonTest.py
adsf
asdf
asdf
asdf

我想:

$ echo 'asdf
asdf
asdf
asdf' | python pythonTest.py
adsf
1
asdf
2
asdf
3
asdf
4

有没有一种不错的pythonic方法,或者只是将自己的计数器添加到for循环的标准解决方案?

0 个答案:

没有答案
相关问题