python script to check if module is present else install module
<p>I have this simple Python script. I want to include some sort of condition that checks for the Python module (in my example below <code>subprocess</code>) 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.</p>

<pre><code>import subprocess
ls_output = subprocess.check_output(['ls'])
print ls_output
</code></pre>

<p>Here is how you can check if pycurl is installed:</p>

<pre><code># 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)
</code></pre>

python python-2.7