2017-04-06 60 views
2

我有一個類創建一個「Test」對象 - 一個基於(描述)外部測試腳本的對象。如何處理不存在的路徑?

的代碼可以在這裏找到:https://codeshare.io/5zlW0W

我使用這個類是這樣的:

from test import Test 

test = Test("/path/to/test") 

這工作得很好,當測試文件存在,但我打了以下錯誤,當它不存在:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/home/user/repos/test.py", line 13, in __init__ 
    self.version = self.get_attribute("version") 
    File "/home/user/repos/test.py", line 33, in get_attribute 
    p = subprocess.Popen([self.path, '--' + attribute], stdout=subprocess.PIPE, universal_newlines=True) 
    File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ 
    restore_signals, start_new_session) 
    File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child 
    raise child_exception_type(errno_num, err_msg) 
FileNotFoundError: [Errno 2] No such file or directory: 'bla' 

所以我的問題有兩個部分:

  1. 處理路徑不存在的情況下,最好的方法是什麼?
  2. 我可以使用函數來定義初始變量來獲取數據嗎?就像我在__init__中所做的那樣?
+0

那麼,如果文件不存在,你想要發生什麼?正確的錯誤信息而不是異常?正在創建的文件? (如果是這樣,用什麼內容?) –

+0

@ das-g理想情況下,如果找不到文件,我希望對象不被初始化。 – Sithling

回答

3

檢查文件使用os.path.exists(file_path)

def get_attribute(self, attribute): 
     """Return a given attribute of the test. 

     Runs a test subprocess with the --<attribute> argument. 
     """ 
     if os.path.exists(self.path): 
      p = subprocess.Popen([self.path, '--' + attribute], stdout=subprocess.PIPE, universal_newlines=True) 
       attr = p.stdout.read().strip("\n") 

      return attr 
0

你總是可以使用標準的OS庫在get_attribute方法存在。

import os 
from test import Test 

if os.path.exists("/path/to/test"): 
    test = Test("/path/to/test") 

如果您還希望確保該文件不爲空,則可以使用

if os.stat("/path/to/test").st_size > 0: 

注意這可能會導致競爭條件:

關於這個問題一個很好的問題,可以發現這裏: How does using the try statement avoid a race condition?

+1

使用'os.path.exists'(同樣適用於'os.stat')會導致測試用例競賽。開放失敗並且抓住異常並拋出你自己的更好。 –

+0

@DanD。對不起,你可以擴大這個意思嗎(測試使用比賽)? – Sithling

+0

謝謝你的評論丹,正在給另一種選擇,但你是正確的。 – Ilhicas