簡體   English   中英

為什么在路徑錯誤時 fileinput 不會拋出錯誤?

[英]Why doesn't fileinput throw an error when there's a bad path?

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 錯誤,則會引發操作系統錯誤。 那么我如何測試壞路徑?

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())

即,僅當您實際遍歷此對象時才打開文件。

雖然我不會推薦第二種方式,因為它與此類腳本應該如何工作的理念背道而馳

你應該盡可能少地解析輸出數據,然后盡快輸出。 這避免了大量輸入的問題,並且如果您的腳本在更大的管道中使用,則會顯着加快處理速度。


關於檢查路徑是否正確:

只要您向下迭代到不存在的文件,迭代器就會拋出異常:

# 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM