python - 如何处理不存在的路径?

标签 python python-3.x

我有一个创建“测试”对象的类 - 一个基于(描述)外部测试脚本的对象。

代码可以在这里找到: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__ 中那样使用函数定义初始变量来获取数据吗?

最佳答案

使用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/

相关文章:

python - 如何在 python 中重新训练机器学习模型,直到获得期望的结果

python - Cython:无法调用共享库的非静态方法

python - 想要通过占位符选择运行时训练的变量

python - 计算时差

python - 在 Python3 中解析 JSON 响应

python - AWS Lambda 导入模块失败

python - 如何旋转 python turtle 对象

python - 我如何使用GAE听Google表格然后运行一组python代码?

python - python 中的 file.write()

python - GDAL (CentOS 8) 安装失败