简体   繁体   English

如何找到 python 模块的绝对路径并导入它?

[英]How can I find a python module absolute path and import it?

I wrote a module and placed it in a directory in my project, for example:我写了一个模块,放在我项目的一个目录下,例如:

projectRoot/src/lib/myModule.py

I have many different applications in my project that are using this module but each resides in a different library and is being executed from a different location, so for example one application might need to insert this module before import in the following way:我的项目中有许多不同的应用程序正在使用此模块,但每个应用程序都驻留在不同的库中,并且从不同的位置执行,因此例如,一个应用程序可能需要在导入之前以下列方式插入此模块:

sys.path.insert(0, '../../src/lib/myModule.py')

while another will use:而另一个将使用:

sys.path.insert(0, '../lib/myModule.py')

On the other hand I can just place the absolute path as such:另一方面,我可以这样放置绝对路径:

sys.path.insert(0, 'home/user/projectRoot/src/lib/myModule.py')

How do I go about this?我该怎么做? I tried the following method but I think I didn't get it right as it game me my project root with the module - projectRoot/myModule.py - which is not correct.我尝试了以下方法,但我认为我没有得到正确的结果,因为它使用模块-projectRoot/myModule.py 游戏我的项目根目录-这是不正确的。

path('myModule.py').abspath()

Bottom line is that I dont know who will need this module and from were it will be executed (python module in Jenkins will also use it) and need to get the correct path before importing the module.底线是我不知道谁需要这个模块以及它会从哪里执行(Jenkins 中的 python 模块也将使用它)并且需要在导入模块之前获取正确的路径。

Tweaking sys.path is likely to lead into confusion, misery and other things, especially when you start thinking about how your addon modules would import other modules of their own.调整sys.path可能会导致混乱、痛苦和其他事情,尤其是当您开始考虑您的插件模块如何导入它们自己的其他模块时。

Instead of trying to manipulate sys.path , your addon modules should be made installable and importable as regular Python packages (see https://packaging.python.org/en/latest/ );而不是试图操纵sys.path ,您的插件模块应该作为常规 Python 包安装和导入(请参阅https://packaging.python.org/en/latest/ ); then you can just import them by name with importlib.import_module() (or use entrypoints to enumerate all of them!).然后您可以使用importlib.import_module()按名称导入它们(或使用入口点枚举所有它们!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM