Home >Backend Development >Python Tutorial >How Can I Programmatically Install Python Modules from PyPI?
Installing third-party modules from the Python Package Index (PyPI) within code may be a desirable operation for various reasons. This article addresses the question of how to achieve this task.
Recommended Approach: Using subprocess to Invoke pip
The officially endorsed method is to employ a subprocess call to invoke pip's command-line interface. This approach ensures compatibility with the installed pip version and adherence to best practices.
Code Sample:
import subprocess import sys def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package])
In this snippet:
This implementation aligns with the official pip guidelines that discourage programmatic usage of pip's code.
The above is the detailed content of How Can I Programmatically Install Python Modules from PyPI?. For more information, please follow other related articles on the PHP Chinese website!