我有一个创建“测试”对象的类 - 一个基于(描述)外部测试脚本的对象。
代码可以在这里找到: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'
所以我的问题分为两部分:
- 处理路径不存在的情况的最佳方法是什么?
- 我可以像在
__init__
中那样使用函数定义初始变量来获取数据吗?
最佳答案
使用os.path.exists(file_path)
检查get_attribute
方法中文件是否存在
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
关于python - 如何处理不存在的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251219/