Installing Python Modules Programatically
Installing Python modules within scripts is a common task. This question explores the possibility of leveraging modules or distutils features for seamless installation of packages like "requests."
Recommended Approach: Subprocess Invocation
The officially endorsed method for installing packages during runtime is to invoke the command-line interface (CLI) of pip via a subprocess. This ensures compatibility with pip versions 10 and above, as the programmatic use of pip has been deprecated and moved to pip._internal.
Code Snippet:
import subprocess import sys def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package])
How it Works:
Alternative Methods (Discouraged)
Some answers suggested alternative methods, but it's important to note that these are not officially supported by pip and may lead to unexpected results.
The above is the detailed content of How Can I Programmatically Install Python Packages Like 'requests'?. For more information, please follow other related articles on the PHP Chinese website!