2017-04-06 62 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