Python:获取导入模块的句柄

2024-06-16 08:57:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个应用程序,让用户可以选择指定一个特定的网络扫描工具(比如nmap、xprobe、p0f),然后使用该工具扫描给定的子网(我不重新实现该工具,只需在shell中调用它并为我的应用程序解析其响应),解析结果并以特定格式存储在DB中。这个应用程序基本上是另一个应用程序的feeder应用程序,它将使用数据库中的数据。在

我已经编写了我的代码,以便所有的故障诊断仪接口都作为插件实现。结构是

Project/
   DBWriter.py 
   Scanner/
      __init__.py
      network_mapper.py
      Scanner.py
      Plugins/
         __init__.py
         nmap.py
         p0f.py
   Others/  

因此,要添加一个新的扫描接口,开发人员只需编写一个工具.py文件(当然是正确的语义)并将其放入Plugins文件夹。在

为了实现这一点,我需要能够在运行时导入正确的python模块。在

^{pr2}$

取决于用户输入的内容

这是我添加的代码

f,p,d = imp.find_module("Plugins")
x = imp.load_module("Plugins",f,p,d)
path_n = x.__path__
f,p,d = imp.find_module("%s"%(tool),path_n)
tool_mod = imp.load_module("%s"%(tool),f,p,d)
tool_mod.scan() #Irrespective of what user enters or what new plugin is  developed, this line does not need to change and will work as long as plug-in has a scan function

代码工作正常。但是,当我试图使用PyInstaller(对于Windows/*Nix平台)将其绑定到一个可执行文件中时,在find_module和load_module方面有很多问题,因此我得到了一个ImportError(可能是因为在可执行文件解压中路径没有正确展开)。在

我的问题是——在Python中有没有其他方法可以让我实现同样的功能(希望可以与PyInstaller一起工作)?在

我之前曾问过这个问题,在PyInstaller中寻找解决办法,但没有人回答,我不得不在Python中寻找解决办法


Tags: 工具path代码用户py应用程序pluginsload
1条回答
网友
1楼 · 发布于 2024-06-16 08:57:04

如果您只需要在Windows上运行,那么我建议您试试py2exe。在

py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.

我们在工作中使用它来加速一个非常大的Python程序,它处理导入的模块。在

相关问题 更多 >