I want to write a script to automatically setup a brand new ubuntu installation and install a django-based app. Since the script will be run on a new server, the Python script needs to automatically install some required modules.
Here is the script.
#!/usr/bin/env python
import subprocess
import os
import sys
def pip_install(mod):
print subprocess.check_output("pip install %s" % mod, shell=True)
if __name__ == "__main__":
if os.getuid() != 0:
print "Sorry, you need to run the script as root."
sys.exit()
try:
import pexpect
except:
pip_install('pexpect')
import pexpect
# More code here...
The installation of pexpect
is success, however the next line import pexpect
is failed. I think its because at runtime the code doesn't aware about the newly installed pexpect
.
How to install and import Python modules at runtime? I'm open to another approaches.
I actually made a module for this exact purpose (impstall)
It's really easy to use:
Github link for issues/contributions
For those who are using pip version greater than 10.x, there is no
main
function forpip
so the alternative approach is usingimport pip._internal as pip
instead ofimport pip
like :Updated answer of Paulo
You can import pip instead of using subprocess:
Another take:
[edit]
You should consider using a requirements.txt along with pip. Seems like you are trying to automate deployments (and this is good!), in my tool belt I have also virtualenvwrapper, vagrant and ansible.
This is the output for me:
I solved my problem using the
imp
module.Actually the code is less than ideal, since I need to hardcode the Python module directory. But since the script is intended for a known target system, I think that is ok.