Skip to content

Instantly share code, notes, and snippets.

@brianspiering
Last active December 16, 2021 18:05
Show Gist options
  • Save brianspiering/46a62532bc8ba3d4fa3f2124aa3c09d0 to your computer and use it in GitHub Desktop.
Save brianspiering/46a62532bc8ba3d4fa3f2124aa3c09d0 to your computer and use it in GitHub Desktop.
Install packages with pip inside a Python .py file
"""Check for 3rd party package, if not present, pip install it.
This is potentially dangerous code. It should only be used for educational purposes.
Defining a requirements.txt is one of the much better options.
"""
from importlib import import_module
module_name = 'pytest'
try:
module = import_module(module_name, package=None)
exec(f'{module_name} = module')
except ModuleNotFoundError:
import pip
import sys
import subprocess
subprocess.check_call([sys.executable, '-m', 'pip', 'install', module_name])
module = import_module(module_name, package=None)
exec(f'{module_name} = module')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment