My Favorite Python Trick

Toz

Elite Member
Jr. VIP
Joined
Oct 24, 2011
Messages
3,227
Reaction score
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:

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.
 
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:

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.
Good idea
 
  • Like
Reactions: Toz
Cool. but, why don't you just build exe file with Pyinstaller and put the needed dll inside the foulder?
Pyinstaller-compiled .exe binaries often appear as scary-looking false positives.
Plus, if inside a working environment when collaborating with a team, it's easier to just deal in .py
Also for Linux.
 
Thanks for this. I am going to implement it.
 
  • Like
Reactions: Toz
Back
Top