Python脚本调用pip.main安装包失败:'module'对象无'main'属性
Installing Python Packages via pip in Python 2.7 (pip 9.0.1)
Working with older Python and pip versions can throw some unexpected curveballs—let's get your package installation script sorted out.
First, here's a revised version of your code that should work reliably in your environment:
try: # Check if both required modules are available import requests import yaml # Note: PyYAML installs under the module name 'yaml' except ImportError: # For pip 9.0.1, the main entry point is still pip.main() import pip # Install the specified versions quietly pip.main(['install', '-q', 'requests==2.0.1', 'PyYAML==3.11']) # After installing, re-import to use the newly installed modules import requests import yaml
Key fixes and explanations:
- Your original code only checked for
requests—ifPyYAMLwas missing butrequestswas present, it wouldn't install PyYAML. The revised code checks both modules in thetryblock. - In pip 9.0.1,
pip._internal.main()isn't the right entry point (that's a change that came in later pip versions), which is why switching to it didn't help. Stick withpip.main()here. - After installing packages at runtime, re-importing the modules ensures the interpreter picks up the newly installed versions immediately.
Alternative (more reliable) approach:
If you still run into issues with pip.main(), using subprocess to call pip directly is often more robust for older Python/pip combinations:
import subprocess import sys try: import requests import yaml except ImportError: # Use sys.executable to ensure we're using the correct pip for this Python instance subprocess.check_call( [sys.executable, '-m', 'pip', 'install', '-q', 'requests==2.0.1', 'PyYAML==3.11'] ) # Re-import the modules after installation import requests import yaml
This method bypasses any issues with importing pip's internal modules and uses the pip that's directly associated with your current Python interpreter.
Content of the question originates from Stack Exchange, asked by Sagar birla
相关产品推荐
相关产品推荐

