代码之家  ›  专栏  ›  技术社区  ›  Drxxd

没有路径黑客的python项目结构

  •  12
  • Drxxd  · 技术社区  · 7 年前

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

    主要的py公司

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

    有没有办法不用这个黑客来做?还是有更好的方法来组织项目结构?

    2 回复  |  直到 7 年前
        1
  •  5
  •   Community Heathro    4 年前

    我认为最好的办法是 sharedlib

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

    setup.py (部分取自 Python-packaging "Minimal Structure" ):

    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 develop pip install -e .

    这样(使用 develop -e 选项)更改 sharedlib/sharedlib/* 共享lib 包-尽管如果您在交互式口译员中工作,可能需要重新启动口译员。这是因为解释器缓存了已经导入的包。

    setuptools

    Setuptools允许您部署项目以在公共目录或临时区域中使用,但无需复制任何文件。 . [...]

    为此,请使用 setup.py develop 命令

    最重要的是你可以 import sharedlib 现在无处不在-无需插入 共享lib PATH PYTHONPATH 因为Python(或者至少是安装它的Python)现在 共享lib

        2
  •  0
  •   AlanK    7 年前

    我们这样做的方式是使用bash入口脚本来编写python脚本。我们的目录结构类似于以下内容:

    /opt/stackoverflow/
                     -> bin
                     -> conf
                     -> lib
                     -> log
    

    然后,我们的lib文件夹包含所有子项目

    /opt/stackoverflow/lib/
                        -> python_algorithms
                        -> python_data_structures
                        -> python_shared_libraries
    

    然后,当我们想要执行python脚本时,我们将通过bin目录中的bash脚本来执行它

    /opt/stackoverflow/bin/
                        -> quick_sort.sh
                        -> merge_sort.sh
    

    如果我们输入一个脚本

    cat merge_sort.sh
    
    #!/bin/bash
    export STACKOVERFLOW_HOME=/opt/stackoverflow
    export STACKOVERFLOW_BIN=${STACKOVERFLOW_HOME}/bin
    export STACKOVERFLOW_LIB=${STACKOVERFLOW_HOME}/lib
    export STACKOVERFLOW_LOG=${STACKOVERFLOW_HOME}/log
    export STACKOVERFLOW_CONF=${STACKOVERFLOW_HOME}/conf
    
    # Do any pre-script server work here
    
    export PYTHONPATH=${PYTHONPATH}:${STACKOVERFLOW_LIB}
    
    /usr/bin/python "${STACKOVERFLOW_LIB}/python_algorithms/merge_sort.py" $* 2>&1