I'm trying to use the importlib library to verify whether the nmap library is installed on the computer executing the script in Python 3.5.2
I'm trying to use importlib.util.find_spec("nmap")
but receive the following error.
>>> import importlib
>>> importlib.util.find_spec("nmap")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'importlib' has no attribute 'util'
Can someone tell me where I'm going wrong?
EDIT
I was able to get the function to work using the following code.
#!/usr/bin/pythonw
import importlib
from importlib import util
#check to see if nmap module is installed
find_nmap = util.find_spec("nmap")
if find_nmap is None:
print("Error")
Try this:
I intend to investigate, but honestly I don't know why one works and the other doesn't. Also, observe the following interactive session:
So...yeah. I am sure this makes perfect sense to someone, but not to me. I will update once I figure it out.
Update:
Comparing this to something like:
I think the difference is that in this case the first
datetime
is a module and the second is a class, while in theimportlib.util
case both are modules. So perhapsmodule.module
is not OK unless the code from both modules has been loaded, whilemodule.class
is OK, because the class code is loaded when the module is imported.Update #2
Nope, it seems like in many cases
module.module
is fine. For example:So perhaps it is something specific to
importlib
.Update #3
As @kfb pointed out in the comments, it does seem to be related to
importlib
specifically. See the following comment from the__init__.py
forimportlib
:importlib/util.py
does importimportlib._bootstrap
so I would assume that this is realted. If my understanding is correct, when you doimport importlib
the submodules will be initialized, but are not initialized for theimportlib
module object that you have imported. At this point, if you dodir(importlib)
you will not seeutil
. Interestingly, after you have tried to accessimportlib.util
and gotten anAttributeError
,util
(along with the other submodules) gets loaded/initialized, and now you can accessimportlib.util
!