setuptools pyproject.toml - 管理所附配置文件的路径

问题描述 投票:0回答:2

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

python setuptools pyproject.toml
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)

但是我需要对所有文件执行此操作,希望在安装工具中采用通用方法。


0
投票

我不确定我是否理解这与

setuptools
有何具体关系,因为这似乎是一种运行时行为(
setuptools
处理构建时行为)。

可能

importlib.resources
(及其回填
importlib_resources
)可以在这里提供帮助。

函数

importlib_resources.files("<NAME OF YOUR ROOT PACKAGE>")
应该允许您遍历软件包安装中的所有文件。

© www.soinside.com 2019 - 2024. All rights reserved.