跨 python 项目共享实用程序模块
在我的 python 项目中共享实用程序模块的最佳目录结构策略是什么?由于公共模块将更新新功能,我不想将它们放在 python 安装目录中。
project1/
project2/
sharedUtils/
从project1我无法使用“import ..\sharedUtils”,还有其他方法吗?我不想对“sharedUtils”位置进行硬编码
提前致谢
What would be the best directory structure strategy to share a utilities module across my python projects? As the common modules would be updated with new functions I would not want to put them in the python install directory.
project1/
project2/
sharedUtils/
From project1 I can not use "import ..\sharedUtils", is there any other way? I would rather not hardcode the "sharedUtils" location
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
目录结构:
根据您显示的目录,您可以从
project1
目录内的foo.py
添加到sharedUtils
的相对路径如下所示:这可以避免对
C:/../sharedUtils
路径进行硬编码,并且只要您不更改目录结构就可以工作。Directory structure:
With the directories as you've shown them, from
foo.py
inside theproject1
directory you can add the relative path tosharedUtils
as follows:This avoids hardcoding a
C:/../sharedUtils
path, and will work as long as you don't change the directory structure.制作一个单独的独立包?并将其放入 python 安装的 /site-packages 中?
在开发模式方面,我个人也最喜欢:使用符号链接和/或
*.pth
文件。Make a separate standalone package? And put it in the /site-packages of your python install?
There is also my personal favorite when it comes to development mode: use of symlinks and/or
*.pth
files.假设您有
sharedUtils/utils_foo
和sharedUtils/utils_bar
。您可以编辑 PYTHONPATH 以包含
sharedUtils
,然后使用在project1
和project2
中导入它们。在 linux 中,您可以编辑 ~/.profile像这样:
使用 PYTHONPATH 环境变量会影响 python 在查找模块时搜索的目录。由于每个用户都可以设置自己的 PYTHONPATH,因此该解决方案非常适合个人项目。
如果您希望计算机上的所有用户都能够导入
sharedUtils
中的模块,那么您可以通过使用
.pth
文件来实现此目的。.pth
文件的具体放置位置可能取决于您的 python 发行版。请参阅 在 Python 中使用 .pth 文件开发。Suppose you have
sharedUtils/utils_foo
andsharedUtils/utils_bar
.You could edit your PYTHONPATH to include
sharedUtils
, then import them inproject1
andproject2
usingIn linux you could do that be editing ~/.profile with something like this:
Using the PYTHONPATH environment variable affects the directories that python searches when looking for modules. Since every user can set his own PYTHONPATH, this solution is good for personal projects.
If you want all users on the machine to be able to import modules in
sharedUtils
, thenyou can achieve this by using a
.pth
file. Exactly where you put the.pth
file may depend on your python distribution. See Using .pth files for Python development.