如何检测模块是否以“可编辑模式"安装? [英] How to detect if module is installed in "editable mode"?
问题描述
我正在像这样通过点子方式安装我的模块:
I'm pip-installing my module like so:
cd my_working_dir
pip install -e .
以后我从Python导入模块时,我能以某种方式检测模块是否以这种可编辑模式安装吗?
When I later import the module from within Python, can I somehow detect if the module is installed in this editable mode?
现在,我只是检查os.path.dirname(mymodule.__file__))
中是否有一个.git文件夹,好吧,仅当那里确实有一个.git文件夹时,该文件夹才有效.有没有更可靠的方法?
Right now, I'm just checking if there's a .git folder in os.path.dirname(mymodule.__file__))
which, well, only works if there's actually a .git folder there. Is there a more reliable way?
推荐答案
我不知道直接检测此问题的方法(例如,询问setuptools
).
I don't know of a way to detect this directly (e.g. ask setuptools
).
您可以尝试通过sys.path
中的路径检测到无法 打包您的软件包.但这很乏味.它也不是防弹的-如果可以通过sys.path到达 ,但是也作为可编辑程序包安装了该怎么办?
You could try to detect that you package can not be reached through the paths in sys.path
. But that's tedious. It's also not bullet proof -- what if it can be reached through sys.path but it's also installed as en editable package?
最好的选择是查看可编辑的安装保留在site-packages
文件夹中的工件.那里有一个名为my_package.egg-link
的文件.
The best option is to look at the artifacts an editable install leaves in your site-packages
folder. There's a file called my_package.egg-link
there.
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_file的第一行,并使用Path()
对其进行解析,以解决斜杠等问题.
Note: to make this a bit more bullet-proof, read only the first line of the egg_link_file and parse it using Path()
as well to account for proper slashes etc.
这篇关于如何检测模块是否以“可编辑模式"安装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!