I would like to add some of my thoughts / conclusions on this topic. I am writing a script that checks all requirements for a user program. There are many checks with python modules.
There's a bit of a problem with
try: import .. except: ..
decision. In my case, one of the python modules called python-nmap , but you import it with import nmap and, as you can see, the name mismatch. Therefore, the test with the solution above returns the result False, and also imports the module on hit, but it may not be necessary to use large memory for a simple test / check.
I also found that
import pip installed_packages = pip.get_installed_distributions()
installed_packages will only install packages using pip . On my system, pip freeze returns through 40 python modules, and installed_packages only has 1 , the one I installed manually (python-nmap).
Another solution, below which I know it , may not be relevant to the question , but I think itβs good practice to keep a separate test function from the one that performs installing it may be useful for some.
A solution that worked for me. It is based on this answer. How to check if a python module exists without importing it
from imp import find_module def checkPythonmod(mod): try: op = find_module(mod) return True except ImportError: return False
NOTE. This solution cannot find a module named python-nmap either, I have to use nmap instead (easy to live with), but in this case the module will not be loaded into memory at all.
Gergely M Sep 07 '17 at 12:04 on 2017-09-07 12:04
source share