Although it may sound trivial how should I import libraries in Python makefiles?
I am creating a basic Python makefile such as:
all: my_file.py python3 my_file.py
However I am using specific libraries inside my_file.py, not included/imported in the basic package, for instance: xlswriter
. So if someone tries to run the code they must type in terminal something similiar to:
$ sudo apt-get install python3-xlsxwriter
So my question is how to adapt my Makefile, so that it is enough for an external user to run the program only by the $ make
command (and it automatically proceeds with installing the package).
Thanks in advance!
Advertisement
Answer
In general, making installation changes for your users is a bad idea. Their system is theirs to control, and if they decide they do not want to install additional packages, and therefore not be able to use your script, that is usually left up to them.
Using sudo
for them is an even worse idea, and may be detected as an attack. What if you made some weird mistake in your code and sudo rm -r
their hard-drive? Respect the permission hierarchy – global installations are up to the super-user, local ones and running the script is up to the user, and doing exactly the work the script is promised to do is up to you – given all requirements are met (which should be listed as well).
The import
itself is not done in the Makefile, but in your Python script. That is where I would detect it, and produce the error that informs the user what they need to do. So in you script I would have something like:
try: import xslwriter #Add as as many imports as you would like to check for. except ModuleNotFoundError as e: print("-E- Failed to import prerequisite {}. Please install prior to running this script.".format(e.name)) exit(1)
You can print
suggestions for installations as well (Detect os
and decide if you suggest yum
or apt
(if a Linux flavor and not Windows), using pip
which always works etc.).
exit(1)
indicates your program halted with an error, and will fail the Makefile recipe as well. This way the script warns properly and works as a standalone as well.