Installing a PyPI module by code



  • Hi!

    I'm trying to install a module from PyPI by code and it returns an error.

    I've tried this:

    import pip
    pip.main(['install', 'package_name'])
    

    and it fails with the output:

    Traceback (most recent call last):
    
    File "", line 2, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/__init__.py", line 16, in main
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/utils/entrypoints.py", line 3, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/cli/main.py", line 10, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/cli/autocompletion.py", line 9, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/cli/main_parser.py", line 7, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/cli/cmdoptions.py", line 23, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/cli/progress_bars.py", line 12, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/utils/logging.py", line 18, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/utils/misc.py", line 33, in
    
    File "/Applications/RoboFont.app/Contents/Resources/lib/python3.7/pip/_internal/locations.py", line 15, in
    
    File "distutils/command/install.pyc", line 18, in
    
    ImportError: cannot import name 'USER_BASE' from 'site' (/Applications/RoboFont.app/Contents/Resources/site.pyc)
    

    Also, I've tried this:

    import sys
    import subprocess
    
    output = subprocess.run([sys.executable, "-m", "pip", "install", "package_name"], capture_output=True)
    
    print(output)
    

    and got almost the same report with USER_BASE can't be imported, and also the same with pip show as subprocess.

    What I'm doing wrong?


Log in to reply