Reputation: 4029
I have a python code which uses paramiko module. By default paramiko is not installed and in order to make sure the code will always run I need to add some sort of a safe import method that tries to import the module and in case of failure will try to install it. What is the most pythonic way to achieve an equivalent code to the following one?
import os, importlib
def SafeImport(module):
while True:
try:
module = importlib.import_module(module)
return module
except Exception as e:
print module + ' is not installed, you will need root privileges to install it. ' + str(e)
os.system('sudo yum --assumeyes install python-pip python-devel')
os.system('sudo pip install ' + module)
paramiko = SafeImport('paramiko')
This is clearly not a cross platform code, it will fail on windows, mac os and even on linux distros without yum
. In fact I can't be sure what version of python with run the script so it is possible that importlib
won't be available to it. What is the general pythonic way to address such issues?
Upvotes: 1
Views: 161
Reputation: 4207
The most pythonic way of doing this is
import paramiko
This produces the following output.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named paramiko
Users can then make an intelligent decision on how to install it on their system. You can, of course, package your software so that paramiko
is installed for them.
Upvotes: 1