Last active
December 16, 2021 18:05
-
-
Save brianspiering/46a62532bc8ba3d4fa3f2124aa3c09d0 to your computer and use it in GitHub Desktop.
Install packages with pip inside a Python .py file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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