- Oct 24, 2011
- 3,227
- 3,588
Often times, when distributing software to people who may have Python already installed, but may not necessarily have the modules required to run your particular software, installed on their machines, I have a solution that has proven time and time again, to be most helpful.
Automatically Install the Required Modules:
I utilize this strategy in virtually everything I write.
Hope you guys get as much use out of this as I do.
Enjoi.
Automatically Install the Required Modules:
Code:
import subprocess, sys, pip
def install(required_package):
subprocess.check_call(sys.executable, '-m', 'pip', 'install', '--upgrade', required_package)
def import_or_install(required_package):
try:
__import__(required_package)
except ImportError:
pip.main(['install', '--upgrade', required_package])
# From here, you can use the above function to use for any modules that are required.
# For example...
import_or_install('concurrent.futures')
import_or_install('selenium')
# etc...
I utilize this strategy in virtually everything I write.
Hope you guys get as much use out of this as I do.
Enjoi.