jebjeb
jebjeb

Reputation: 125

python script to check if module is present else install module

I have this simple Python script. I want to include some sort of condition that checks for the Python module (in my example below subprocess) before running it. If the module is not present, install the module then run the script. If the module is present, skip the installation of the module and run the script. I am struggling with most of the similar scenarios I am seeing online.

import subprocess
ls_output = subprocess.check_output(['ls'])
print ls_output

Upvotes: 3

Views: 6376

Answers (1)

2ps
2ps

Reputation: 15926

Here is how you can check if pycurl is installed:

# if you want to now install pycurl and run it, it is much trickier 
# technically, you might want to check if pip is installed as well
import sys
import pip

def install(package):
    pip.main(['install', package])

try:
    import pycurl
except ImportError:
    print 'pycurl is not installed, installing it now!'
    install('pycurl')

# not recommended because http://stackoverflow.com/questions/7271082/how-to-reload-a-modules-function-in-python
import pycurl
. . . .
# better option:
print 'just installed pycurl, please rerun this script at your convenience'
sys.exit(1)

Upvotes: 4

Related Questions