我正在开发一个带有使用入口点的插件的 Slack 机器人。我想在运行时动态添加插件。
我有一个具有以下结构的项目:
+ ~/my_project_dir/
+ my_projects_python_code/
+ plugins/
- plugin1.py
- plugin2.py
- ...
- pluginN.py
- setup.py
- venv/
- install.sh
My setup.py
文件看起来像这样:
from setuptools import setup, find_packages
setup(
name="My_Project_plugins",
version="1.0",
packages=['plugins'],
entry_points="""
[my_project.plugins]
plugin1 = plugins.plugin1:plugin1_class
plugin2 = plugins.plugin2:plugin2_class
...
pluginN = plugins.pluginN:pluginN_class
"""
)
Running sudo install.sh
执行以下操作:
将需要的文件复制到/usr/share/my_project_dir/
激活 virtualenv 在/usr/share/my_project_dir/venv/bin/activate
Run: python setup.py develop
这按预期工作并正确设置我的入口点,以便我可以通过机器人使用它们。
但我希望能够添加一个插件setup.py
并能够在机器人运行时使用它。所以我想添加一行:pluginN+1 = plugins.pluginN+1:pluginN+1_class
并且有插件N+1可供使用。
我尝试/学到的:
After /usr/share/my_project_dir/venv/bin/activate
我打开一个 Python 交互式 shell 并迭代pkg_resources.iter_entry_points()
,其中列出了从 setup.py 初始状态加载的所有内容(即plugin1到pluginN)
如果我添加一行setup.py
并运行sudo python setup.py develop
并使用相同的 Python shell 再次迭代,它不会拾取新插件,但如果我退出 shell 并重新打开它,则会拾取新插件。
-
我注意到当我安装机器人时,部分输出显示:
-
Copying My_Project_plugins-1.0-py2.7.egg to /usr/share/my_project-dir/venv/lib/python2.7/site-packages
-
When I cd /usr/share/my_project_dir/
,激活我的 virtualenv,然后运行setup.py
从外壳上看,它说:
Creating /usr/local/lib/python2.7/dist-packages/My_Project-plugins.egg-link (link to .)
My_Project-plugins 1.0 is already the active version in easy-install.pth
我需要做一些类似的事情来加载虚拟插件以进行测试。这与您的用例略有不同,因为我专门试图避免需要在包中定义入口点(因为它只是测试代码)。
我发现我可以动态地将条目插入到 pkg_resources 数据结构中,如下所示:
import pkg_resources
# Create the fake entry point definition
ep = pkg_resources.EntryPoint.parse('dummy = dummy_module:DummyPlugin')
# Create a fake distribution to insert into the global working_set
d = pkg_resources.Distribution()
# Add the mapping to the fake EntryPoint
d._ep_map = {'namespace': {'dummy': ep}}
# Add the fake distribution to the global working_set
pkg_resources.working_set.add(d, 'dummy')
这在运行时向“namespace”添加了一个名为“dummy”的入口点,这将是“dummy_module.py”中的类“DummyPlugin”。
这是通过使用 setuptools 文档和对象上的 dir() 来根据需要获取更多信息来确定的。
文档在这里:http://setuptools.readthedocs.io/en/latest/pkg_resources.html http://setuptools.readthedocs.io/en/latest/pkg_resources.html
你可能会特别看一下http://setuptools.readthedocs.io/en/latest/pkg_resources.html# located-plugins http://setuptools.readthedocs.io/en/latest/pkg_resources.html#locating-plugins如果您需要做的只是加载刚刚存储到本地文件系统的插件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)