简体   繁体   English

当使用py.test测试该模块时,如何通过相对于Python模块的路径打开文件?

[英]How to open a file by its path relative to the Python module, when that module is tested with py.test?

I have a module inside a package which figures out the path of the invoking python program: 我在包中有一个模块,可以弄清楚调用python程序的路径:

pathname = os.path.dirname(os.path.realpath(__file__))

from where it will pick up a mydata.json to read some parameter values. 从那里它将拾取mydata.json来读取一些参数值。

This works fine when executing the script using python xyz.py 使用python xyz.py执行脚本时,此方法工作正常

But the same stuff, when done using py.test at the directory, the path just points to some binary: /home/user/venv/bin/data/data.json 但是同样的东西,当在目录中使用py.test完成时,路径仅指向一些二进制文件: /home/user/venv/bin/data/data.json

Basically the calling script is assumed to be py.test itself, which is located in the venv/bin . 基本上,假定调用脚本为py.test本身,位于venv/bin

How to overcome this problem ? 如何克服这个问题? I want to fetch the path of the script which in turn is being processed by py.test itself (via the module). 我想获取脚本的路径,而该路径又由py.test本身(通过模块)处理。

If i understand the problem correctly you should be using 如果我正确理解问题,则应该使用

import json
import os

path_to_current_file = os.path.realpath(__file__)
current_directory = os.path.split(path_to_current_file)[0]
path_to_file = os.path.join(current_directory, "mydata.json")
with open(path_to_file) as mydata:
    my_json_data = json.load(mydata)

Slightly different version from the one offered above: 与上面提供的版本略有不同:

path_to_current_file = os.path.realpath(__file__)
current_directory = os.path.dirname(path_to_current_file)
path_to_file = os.path.join(current_directory, "mydata.json")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM