gpt4 book ai didi

python - 具有多个入口点和集中(配置)文件的结构 python 项目

转载 作者:行者123 更新时间:2023-12-05 08:10:04 44 4
gpt4 key购买 nike

我正在编写一堆一起工作的 python 脚本,例如 tool1.py 将一些数据加载到数据库表中,tool2.py 从该表中读取数据,进行一些计算并将结果写入另一个表中,然后daemon1.py 是一个提供结果的网络服务器。每个工具和守护进程都有一大堆支持文件(只有那个工具需要),并且需要自己的目录。此外,我确实有一些代码在所有工具之间共享,例如 config.py 和 database.py。直觉上,我是这样构建项目的:

/README.md
/requirements.txt
/config.py # contains shared configuration
/database.py # shared code to connect to the database
/tool1/
tool1.py # entrypoint
[...] # bunch of other files only needed by tool1
/tool2/
tool2.py #entrypoint
[...] # bunch of other files only needed by tool2
/deamon1/
daemon1.py #entrypoint
[...] # bunch of other files only needed by daemon1

然后我使用命令 python tool1/tool1.py 运行我的工具和守护进程。然而,这里的问题是 tool1.py 如何访问 config.py/database.py。我考虑了以下选项,会对什么被认为是 python 中的“正确”方式感兴趣,或者我可能错过的任何替代方案(可能是布局项目的不同方式)。指向权威答案的链接将奖励额外的业力。

  1. 将 config.py/database.py 文件符号链接(symbolic link)到子目录。不太喜欢它,因为它让我的编辑感到困惑,而且似乎让事情变得比必要的更复杂。
  2. 在我安装在我的 virtualenv 中的一些单独的包中制作 config.py/database.py。 不喜欢它,因为我也经常更改这些文件,我想将它们保存在同一个 git 仓库中。
  3. 更改 tool1.py 顶部的 sys.path。这导致每个文件顶部有 4 行,加上 sysos 模块,除了设置这些项目外没有其他原因。
import os
import sys
sys.path.append(os.path.join(os.path.abspath(
os.path.dirname(__file__)), ".."))
  1. 将顶层路径添加到 $PYTHONPATH
  2. 为 tool1.py/tool2.py/daemon1.py 创建顶层入口点,内容类似(将 tool1 目录重命名为 tool1dir 后)
from tool1dir import tool1
tool1.run()
  1. 将 config.py/database.py 放入一个单独的包中,并从每个子目录对该目录进行符号链接(symbolic link)

如前所述,想听听执行此操作的 pythonesque 方式,或任何建议或偏好。

最佳答案

来自 Shinbero another question :

import sys
sys.path.insert(0,'..')
import database

目录可以通过添加返回到它的位置:

sys.path.insert(0,'tool1') #tool1 is replaced with your directory you are calling from.

您使用第三种方法的变体来解决这个问题。

关于python - 具有多个入口点和集中(配置)文件的结构 python 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28580962/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com