import fileinput
def main()
try:
lines = fileinput.input()
res = process_lines(lines)
...more code
except Exception:
print('is your file path bad?')
if __name__ == '__main__':
main()
当我使用错误的路径运行此代码时,它不会引发错误,但是文档说如果发生IO错误,则会引发OS错误。那我该如何测试错误的路径呢?
答案 0 :(得分:4)
fileinput.input()
返回一个迭代器,而不是一个临时列表:
In [1]: fileinput.input()
Out[1]: <fileinput.FileInput at 0x7fa9bea55a50>
此功能的正确使用是通过for
循环完成的:
with fileinput.input() as files:
for line in files:
process_line(line)
或使用转化列表:
lines = list(fileinput.input())
即仅当您实际遍历此对象时,文件才会打开。
尽管我不推荐第二种方法,因为它是counter to the philosophy of how such scripts are supposed to work。
您应该尽可能少地解析输出数据,然后尽快将其输出。这样可以避免输入较大的问题,如果在较大的管道中使用脚本,则可以大大加快处理速度。
关于检查路径是否正确:
一旦您迭代到不存在的文件,迭代器将引发异常:
# script.py
import fileinput
with fileinput.input() as files:
for line in files:
print(repr(line))
$ echo abc > /tmp/this_exists
$ echo xyz > /tmp/this_also_exists
$ python script.py /tmp/this_exists /this/does/not /tmp/this_also_exists
'abc\n'
Traceback (most recent call last):
File "/tmp/script.py", line 6, in <module>
for line in files:
File "/home/mrmino/.pyenv/versions/3.7.7/lib/python3.7/fileinput.py", line 252, in __next__
line = self._readline()
File "/home/mrmino/.pyenv/versions/3.7.7/lib/python3.7/fileinput.py", line 364, in _readline
self._file = open(self._filename, self._mode)
FileNotFoundError: [Errno 2] No such file or directory: '/this/does/not'