Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if module exists, if not install it

I want to check if a module exists, if it doesn't I want to install it.

How should I do this?

So far I have this code which correctly prints f if the module doesn't exist.

try:     import keyring except ImportError:     print 'f' 
like image 649
dotty Avatar asked Dec 24 '10 17:12

dotty


People also ask

How do you check if a module is installed in Python and if not install it within the code?

A quick way is to use python command line tool. Simply type import <your module name> You see an error if module is missing.

How do I know if a Python module is installed or not?

To check all the installed Python modules, we can use the following two commands with the 'pip': Using 'pip freeze' command. Using 'pip list command.

How do I know what Python modules I have?

You can manually go and check the PYTHONPATH variable contents to find the directories from where these built in modules are being imported. Running "python -v"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built in modules.


2 Answers

import pip  def import_or_install(package):     try:         __import__(package)     except ImportError:         pip.main(['install', package])        

This code simply attempt to import a package, where package is of type str, and if it is unable to, calls pip and attempt to install it from there.

like image 160
ewil Avatar answered Oct 06 '22 01:10

ewil


Here is how it should be done, and if I am wrong, please correct me. However, Noufal seems to confirm it in another answer to this question, so I guess it's right.

When writing the setup.py script for some scripts I wrote, I was dependent on the package manager of my distribution to install the required library for me.

So, in my setup.py file, I did this:

package = 'package_name' try:     return __import__(package) except ImportError:     return None 

So if package_name was installed, fine, continue. Else, install it via the package manager which I called using subprocess.

like image 27
user225312 Avatar answered Oct 05 '22 23:10

user225312