A lot of software packages require users of the system to install a set of dependencies first before they can use the software. (This is a general question not specific to python, but I'll speak in context of python.). Can't we make the python module install its own dependencies before executing the code if the dependencies are not already installed. This should be doable with the help of system
or subprocess
calls but I rarely see people doing this.
For example lets say lib
is a python library that needs to be used in the python file main.py :
import os
try:
import lib
except:
os.system('pip install pdir')
import lib
# Can make use of lib now
Is there anything potentially wrong with this approach? Could doing something like this cause problems for big projects?
Note : The advantage here is that a user using the file does not have to install the dependencies separately, he can simply run python main.py
. And the second thing that I realize is that such approach makes sense only when virtualenv
is being used.
You should never do this - pip doesn't have dependency resolution so there's no guarantee that you'll get a certain version. Dependencies should be installed using setup.py
, requirements.txt
or a different approach.
You also shouldn't need user permissions or sudo to install the packages just for running the code. The user should be aware of the packages that are needed for installing your package as they may come from PyPI or the OS's package system or an internal company PyPI mirror - and silently installing dependencies is not a good idea in that case.
You could always consider using a more advanced print statement to inform the user.
try:
import ConfigParser
except ImportError as err:
print '\n'.join([i + ''.join(str(err).split(' ')[-1:]) for i in ['$ pip install ', '$ easy_install ']])
You can recommend them installing the missing package this way.
$ pip install ConfigParser
$ easy_install ConfigParser
Additionally you could consider having a ImportError be reason to recommend the user to run their ./setup.py
or ./INSTALL
instead of just the missing module.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.