我的 Python 应用程序可以以正常方式安装,也可以在开发/可编辑模式下安装pip,如下所示:
virtualenv my_app
source my_app/bin/activate
pip install -e my_app
Run Code Online (Sandbox Code Playgroud)
如何创建一个函数来检查我的 virtualenv 并检查我的应用程序是否在开发/可编辑模式下运行?
sys模块中是否有任何“标志” ?
动机:在开发模式和生产中具有不同的配置。
编辑:我比较了virtualenv和包目录。
import os
import sys
import pkg_resources
main_pkg = 'my_app'
package_dir = pkg_resources.resource_filename(main_pkg, '__init__.py')
virtualenv_dir = os.path.dirname(os.path.dirname(sys.executable))
common_path = os.path.commonprefix([package_dir, virtualenv_dir])
is_dev_mode = not common_path.startswith(virtualenv_dir)
Run Code Online (Sandbox Code Playgroud)
我测试package_dir是否是virtualenv_dir的子目录:如果它不是子目录,那么我处于开发模式。
编辑2:
有没有更可靠的解决方案?
我想知道环境中是否没有数据/标志可以清楚地向我表明我的应用程序正在开发模式下运行。
如果另一个依赖项也处于开发模式会发生什么?
使用来自pip我们的代码可以确定这一点:
import pip
import pkg_resources
# I've done `pip install -e .` for a git repo I'm working in inside
# a virtualenv
distributions = {v.key: v for v in pkg_resources.working_set}
# >>> distribution
# pre-commit 0.9.3 (/home/asottile/workspace/pre-commit)
distribution = distributions['pre-commit']
# Below is approximately how `pip freeze` works, see the end of
# the answer for a simpler approach, still using pip
# Turn into a pip FrozenRequirement (I'm using pip 9.0.1, it may
# be different for your version)
# I've passed an empty list for the second argument (dependency_links)
# I don't think it's necessary?
frozen_requirement = pip.FrozenRequirement.from_dist(distribution, [])
# Query whether the requirement is installed editably:
print(frozen_requirement.editable)
Run Code Online (Sandbox Code Playgroud)
它的神奇之处在于 pip( pip.utils) 中的一个小函数:
def dist_is_editable(dist):
"""Is distribution an editable install?"""
for path_item in sys.path:
egg_link = os.path.join(path_item, dist.project_name + '.egg-link')
if os.path.isfile(egg_link):
return True
return False
Run Code Online (Sandbox Code Playgroud)
在dist在此是一个pkg_resources分布(如我们上面获得的)。您当然可以dist_is_editable直接使用该函数而不是通过FrozenRequirement:
# With `distribution` as above:
from pip.utils import dist_is_editable
print(dist_is_editable(distribution)) # True in my case ;)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1168 次 |
| 最近记录: |