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
  • 22,498
  • 29
  • 129
  • 265

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,659
  • 2
  • 13
  • 43