1

I'm trying to install pip modules automatically:

try:
    import paramiko
except ImportError:
    import pip
    if hasattr(pip, 'main'):
        print('Method 1')
        pip.main(['install', 'paramiko'])
    else:
        pip._internal.main(['install', 'paramiko'])

    import paramiko

But it doesn't work in this environment:

  • Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
  • pip 19.2.3 from c:\python37\lib\site-packages\pip (python 3.7)

And the error is

Traceback (most recent call last):
  File "invoke-pip.py", line 4, in <module>
    import paramiko
ModuleNotFoundError: No module named 'paramiko'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "invoke-pip.py", line 11, in <module>
    pip._internal.main(['install', 'paramiko'])
AttributeError: module 'pip' has no attribute '_internal'

What should I use?

daisy
  • 21,114
  • 28
  • 118
  • 236
  • 5
    "I'm trying to install pip modules automatically"—ugh, please don't do this. Declare your dependencies and let me install them, or build a package. – Chris Mar 07 '22 at 02:14
  • 1
    perhaps you could just use a [requirements file?](https://pip.pypa.io/en/stable/reference/requirements-file-format/) – Freddy Mcloughlan Mar 07 '22 at 02:45

1 Answers1

0

Thing is you are catching the wrong Exception. ImportError was in python 2.x and from python 3.x it has been renamed to ModuleNotFoundError.

Here is the fixed code for the same


try:
    import paramiko
except (ImportError, ModuleNotFoundError): # This will handle both for python 2.x and 3.x
    import pip
    if hasattr(pip, 'main'):
        print('Method 1')
        pip.main(['install', 'paramiko'])
    else:
        pip._internal.main(['install', 'paramiko'])

    import paramiko

As @Chris said, declare a requirements.txt file and let the users install packages. This will ensure the exact version of package is installed that is used while the development of your program.

tbhaxor
  • 1,315
  • 2
  • 9
  • 35