构建没有路径黑客的python项目 [英] Structuring python projects without path hacks

查看:261
本文介绍了构建没有路径黑客的python项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在多个项目中使用的共享python库,因此结构如下:

I have a shared python library that I use in multiple projects, so the structure looks like this:

Project1
    main.py <--- (One of the projects that uses the library)
...
sharedlib
    __init__.py
    ps_lib.py
    another.py

现在在每个项目的 main.py 中,我使用以下命令使其有效:

Now in each project's main.py I use the following hack to make it work:

import os
import sys
sys.path.insert(0, os.path.abspath('..'))

import sharedlib.ps_lib
...

有没有一种方法可以不使用此技巧?还是有更好的方法来组织项目结构?

Is there a way to do it without using this hack? Or is there a better way to organize the projects structure?

推荐答案

我认为最好的方法是使 sharedlib 一个真正的软件包。这意味着要稍微改变一下结构:

I think the best way would be to make sharedlib a real package. That means changing the structure a bit:

sharedlib/
    sharedlib/
        __init__.py
        ps_lib.py
        another.py
    setup.py

并在 setup.py (部分取自 Python-包装最小结构():

from setuptools import setup

setup(name='sharedlib',
      version='0.1',
      description='...',
      license='...',
      packages=['sharedlib'],   # you might need to change this if you have subfolders.
      zip_safe=False)

然后使用 python setup.py开发 pip install -e。 sharedlib 包。

那样(使用 develop -e 选项)更改 sharedlib / sharedlib / * 文件内容的更改将可见,而无需重新安装 sharedlib 软件包-尽管如果您使用的是交互式解释器,则可能需要重新启动解释器。这是因为解释器会缓存已导入的软件包。

That way (using the develop or -e option) changes to the contents of sharedlib/sharedlib/* files will be visible without re-installing the sharedlib package - although you may need to restart the interpreter if you're working in an interactive interpreter. That's because the interpreter caches already imported packages.

来自 setuptools 文档:


Setuptools允许您部署项目以在公共目录或暂存区域中使用,但无需复制任何文件。 因此,您可以在每个项目的签出目录中编辑它们的代码,并且仅在更改项目的C扩展名或类似编译的文件时才需要运行构建命令。 [...]

为此,请使用 setup.py development 命令。

(强调我的意思)

最重要的是,您现在可以随处导入共享库 -无需将 sharedlib 包插入 PATH PYTHONPATH 不再是因为Python(或至少安装了Python的Python)现在将 sharedlib 像对待其他已安装的软件包一样对待。

The most important thing is that you can import sharedlib everywhere now - no need to insert the sharedlib package in the PATH or PYTHONPATH anymore because Python (or at least the Python where you installed it) now treats sharedlib like any other installed package.

这篇关于构建没有路径黑客的python项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆