【问题标题】:Why doesn't fileinput throw an error when there's a bad path?为什么路径错误时 fileinput 不抛出错误?
【发布时间】:2020-10-26 16:51:17
【问题描述】:
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 错误,则会引发操作系统错误。那我该如何测试坏路径呢?

【问题讨论】:

  • 当你尝试读取/迭代input()的结果时会抛出错误。也许函数process_lines 隐藏了错误?

标签: python file-io


【解决方案1】:

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'

【讨论】:

  • 那么我怎么知道它是否是一个错误的文件路径?
  • @TheRealFakeNews 能回答你的问题吗?
猜你喜欢
  • 1970-01-01
  • 2013-03-24
  • 2011-04-18
  • 2017-05-26
  • 2021-11-20
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多