I am trying to make a python script that makes sure that a specific module, 'lxml' is installed.
To do this I have found the following:
help('modules')
This lists the module I am looking for, but I cannot figure out how to specifically identify lxml is listed. It doesn't appear that I can perform any other methods on the command, nor have I been able to assign the output of the command to a variable.
I.E. The below commands do not work
text = help('modules')
(help('modules')).find('lxml')
help.('modules').find('lxml')
Any ideas of how I should approach this?
CodePudding user response:
It is not necessarily clear what "installed" means, since different modules have different installations, paths, binaries, requirements, and so on.
This is why it might be best and also most cost effective to try to import the module, that way to know for a fact that it is installed. This can be done with exception handling as follows:
try:
__import__("lxml")
print("lxml is installed!")
except ImportError as e:
# This means that lxml is not installed
print("lxml is not installed!")
CodePudding user response:
If you try importing a module that you don't installed it will throw you a ModuleNotFoundError
. You can use that to create a try
, except
block.
try:
import lxml
print("module 'lxml' is installed")
except ModuleNotFoundError:
print("module 'lxml' is not installed")
You can even install lxml adding the command below.
try:
import lxml
print("module 'lxml' is installed")
except ModuleNotFoundError:
print("module 'lxml' is not installed")
print("installing 'lxml'")
import pip
pip(['install', 'lxml'])