python - 从非当前目录打开非 py 文件的正确且故障安全的方法
python - proper and fail-safe way to open non py file from not current directory
从非当前目录打开非 py 文件的正确且安全的方法是什么?
更具体地说,我有一个方法,它使用 JSON 模式验证 API 响应,包含在文件 schema.json 中:
def foo():
json_data = collect_json_data()
schema = json.load(open('./schema/schema.json'))
jsonschema.validate(json_data, schema)
并得到如下项目结构:
D:\projects\project-pytest\.
│ .gitignore
│ LICENSE
│ README.md
│ requirenments.txt
│ runner_01.cmd
│ structure.txt
│
├───tests
│ │ runner_02.cmd
│ │ file_with_tests.py
│ │
│ ├───schema
│ │ schema.json
我的目标是 运行 不仅通过执行命令 python -m pytest file_with_tests.py
从目录 project-pytest\tests\
进行测试,而且通过执行 runner_01.cmd
从父目录进行测试,使用命令python -m pytest -v .\tests\file_with_tests.py
里面。
现在第二种方式失败 FileNotFoundError: [Errno 2] No such file or directory: './schema/schema.json'
。
我尝试使用 import os
:
schema_path = os.path.abspath('schema.json')
schema = json.load(open(schema_path))
但在这种情况下,绝对路径会忽略 schema.json
父目录 - FileNotFoundError: [Errno 2] No such file or directory: 'D:\Git\testarea-pytest\schema.json'
.
我应该如何打开放在不同子目录中的 schema.json
并能够执行 运行 命令:
python -m pytest -v .\tests\file_with_tests.py
来自 project-pytest
文件夹
和
python -m pytest -v file_with_tests.py
来自 project-pytest\tests\
文件夹
没有因为 FileNotFoundError
.
而导致测试失败
如果您乐于将项目打包,pkgutil.get_data()
可以帮助从文件系统中的资源位置进行抽象。
解决了从另一端实现我的目标的问题 - 我将 runner_01.cmd
更改为:
python -m pytest -v file_with_tests.py
对此:
cd ./tests/
python -m pytest -v file_with_tests.py
现在可以从项目文件夹运行测试,也可以通过简单的 cmd 脚本运行器从测试文件夹运行测试。不能明确地说这是否是一个问题,但用户很高兴。
从非当前目录打开非 py 文件的正确且安全的方法是什么?
更具体地说,我有一个方法,它使用 JSON 模式验证 API 响应,包含在文件 schema.json 中:
def foo():
json_data = collect_json_data()
schema = json.load(open('./schema/schema.json'))
jsonschema.validate(json_data, schema)
并得到如下项目结构:
D:\projects\project-pytest\.
│ .gitignore
│ LICENSE
│ README.md
│ requirenments.txt
│ runner_01.cmd
│ structure.txt
│
├───tests
│ │ runner_02.cmd
│ │ file_with_tests.py
│ │
│ ├───schema
│ │ schema.json
我的目标是 运行 不仅通过执行命令 python -m pytest file_with_tests.py
从目录 project-pytest\tests\
进行测试,而且通过执行 runner_01.cmd
从父目录进行测试,使用命令python -m pytest -v .\tests\file_with_tests.py
里面。
现在第二种方式失败 FileNotFoundError: [Errno 2] No such file or directory: './schema/schema.json'
。
我尝试使用 import os
:
schema_path = os.path.abspath('schema.json')
schema = json.load(open(schema_path))
但在这种情况下,绝对路径会忽略 schema.json
父目录 - FileNotFoundError: [Errno 2] No such file or directory: 'D:\Git\testarea-pytest\schema.json'
.
我应该如何打开放在不同子目录中的 schema.json
并能够执行 运行 命令:
python -m pytest -v .\tests\file_with_tests.py
来自 project-pytest
文件夹
和
python -m pytest -v file_with_tests.py
来自 project-pytest\tests\
文件夹
没有因为 FileNotFoundError
.
如果您乐于将项目打包,pkgutil.get_data()
可以帮助从文件系统中的资源位置进行抽象。
解决了从另一端实现我的目标的问题 - 我将 runner_01.cmd
更改为:
python -m pytest -v file_with_tests.py
对此:
cd ./tests/
python -m pytest -v file_with_tests.py
现在可以从项目文件夹运行测试,也可以通过简单的 cmd 脚本运行器从测试文件夹运行测试。不能明确地说这是否是一个问题,但用户很高兴。