我正在编写一个从 stdin 获取输入的 python 脚本,并希望跟踪来自 stdin 的输入的行号。
我可以自己创建一个计数器,但我感觉python会自动跟踪行号,因此会浪费计算。我还没有找到如何获取/打印该号码。
我已经阅读并尝试了 .tell() 方法,但它跟踪字符(或字节)而不是行。当输入来自标准输入时,它似乎也失败了。它抛出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循环中的标准解决方案?