【问题标题】:How to detect if module is installed in "editable mode"?如何检测模块是否以“可编辑模式”安装?
【发布时间】:2017-09-07 00:10:12
【问题描述】:

我正在像这样 pip 安装我的模块:

cd my_working_dir
pip install -e .

当我稍后从 Python 中导入模块时,我能否以某种方式检测模块是否以这种可编辑模式安装?

现在,我只是在检查os.path.dirname(mymodule.__file__)) 中是否有一个 .git 文件夹,好吧,只有当那里实际上有一个 .git 文件夹时才有效。有没有更靠谱的方法?

【问题讨论】:

  • @WarrenP 不,它解释了如何在可编辑模式下安装模块。我正在寻找一种很好的方法来检测它(与常规安装相比)。
  • 听起来是一个非常丑陋的细节。由于这可能会在 setuptools 的任何次要版本中发生变化,你怎么知道你的 hack 什么时候坏了?
  • 这似乎与similar post有关。

标签: python pip


【解决方案1】:

我不知道有什么方法可以直接检测到这一点(例如,询问 setuptools)。

您可以尝试检测您的包不能通过sys.path 中的路径到达。但这很乏味。它也不是防弹的——如果它可以通过 sys.path 访问但它安装为可编辑的包怎么办?

最好的选择是查看可编辑安装在您的site-packages 文件夹中留下的工件。那里有一个名为my_package.egg-link 的文件。

from pathlib import Path

# get site packages folder through some other magic

# assuming this current file is located in the root of your package
current_package_root = str(Path(__file__).parent.parent)

installed_as_editable  = False
egg_link_file = Path(site_packages_folder) / "my_package.egg-link"
try:
    linked_folder = egg_link_file.read_text()
    installed_as_editable = current_package_root in linked_folder
except FileNotFoundError:
    installed_as_editable = False

注意:为了更防弹,请只读取egg-link 文件的第一行并使用Path() 解析它,并考虑适当的斜杠等。

【讨论】:

    【解决方案2】:

    另一种解决方法:

    将“不安装”文件放入您的包中。这可以是README.mdnot_to_install.txt 文件。使用任何非 pythonic 扩展,以防止该文件安装。然后检查该文件是否存在于您的包中。

    建议的源码结构:

    my_repo
    |-- setup.py
    `-- awesome_package
        |-- __init__.py
        |-- not_to_install.txt
        `-- awesome_module.py
    

    setup.py:

    # setup.py
    from setuptools import setup, find_packages
    
    setup(
        name='awesome_package',
        version='1.0.0',
    
        # find_packages() will ignore non-python files.
        packages=find_packages(),
    )
    

    __init__.py 或 awesome_module.py:

    import os
    
    # The current directory
    __here__ = os.path.dirname(os.path.realpath(__file__))
    
    # Place the following function into __init__.py or into awesome_module.py
    
    def check_editable_installation():
        '''
            Returns true if the package was installed with the editable flag.
        '''
        not_to_install_exists = os.path.isfile(os.path.join(__here__, 'not_to_install.txt'))
        return not_to_install_exists
    

    【讨论】:

      猜你喜欢
      • 2018-12-19
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 2017-01-27
      • 2023-01-23
      相关资源
      最近更新 更多