setuptools pyproject.toml - 管理封闭配置文件的路径
在使用 pyproject.toml 和 setuptools 的时候,我怎么才能确保我的程序能够动态找到和 Python 代码在同一个目录下的配置文件呢?
在使用 pip 安装后,文件的位置是:
:
c:\dist\venvs\ranchercli\lib\site-packages\ranchercli\ranchercli-projects.json
c:\dist\venvs\ranchercli\lib\site-packages\ranchercli\ranchercli.py
c:\dist\venvs\ranchercli\scripts\ranchercli.exe
:
但是当我运行:
# same dir:
ranchercli.exe --ns='keycloak' --env=prod --refresh
20240322095209.115|ERROR|C:\dist\venvs\ranchercli\Lib\site-packages\ranchercli\ranchercli.py:89|--projectfile=./ranchercli-projects.json not found
# relative:
20240322101246.345|ERROR|C:\dist\venvs\ranchercli\Lib\site-packages\ranchercli\ranchercli.py:89|--projectfile=../lib/site-packages/ranchercli/ranchercli-projects.json not found
我只得到了完整的路径,但这个路径在每次安装时都会变化:
C:\\dist\\venvs\\ranchercli\\Lib\\site-packages\\ranchercli\\ranchercli-projects.json
2 个回答
0
像@phd提到的那样,有一种解决方法是使用pathlib从__file__
获取文件路径。
parser.add_argument('--projectfile', help="json projectlist file", default='./ranchercli-projects.json')
:
if not os.path.isfile(args.projectfile):
if args.projectfile.startswith('.'):
args.projectfile = pathlib.Path(__file__).parent.absolute() / pathlib.Path(args.projectfile)
if not os.path.isfile(args.projectfile):
log.error(f"--projectfile={args.projectfile}, not found")
sys.exit(-1)
不过我需要对所有文件都这样做,希望在setuptools中有一个通用的方法。
1
我不太确定这和 setuptools
有什么具体关系,因为这似乎是运行时的行为,而 setuptools
主要处理的是构建时的行为。
可能 importlib.resources
(还有它的补充版本 importlib_resources
)可以在这里提供帮助。
使用 importlib_resources.files("<你的根包名称>")
这个函数,可以让你查看你安装的包里面的所有文件。