-1

I'm trying to figure this out as I am new to python. My program requires a few packages to be installed such as pip, bs4, python3, gedit etc.

What I would like to happen is. If the user runs the program but doesn't have the installed packages to ask the user to install them first and exit. I want to say this can be accomplished with an 'if elif else' with a try-except statement. But I'm not sure if this is the best approach or how I would incorporate this into my program. Any help would be very appreciated!

  • package the program as a PyPI package, then ask user to install from PyPI or run setup.py manually. – Marat May 06 '20 at 20:58
  • Does this answer your question? [Error handling when importing modules](https://stackoverflow.com/questions/3131217/error-handling-when-importing-modules) – Tomerikoo May 06 '20 at 20:59
  • Does this answer your question? [How do I package a python application to make it pip-installable?](https://stackoverflow.com/questions/5360873/how-do-i-package-a-python-application-to-make-it-pip-installable) – Booboo May 06 '20 at 21:05
  • There are plenty of existing resources on packaging Python programs, which aspects of this particular situation do they not cover? – AMC May 06 '20 at 22:43

2 Answers2

1

If you decide to go with try-except statements, you can do it like this:

try:
    import pandas as pd
except ImportError as e:
    pass  # or give an alternative message, do whatever
sander
  • 1,340
  • 1
  • 10
  • 20
1

As @Sandertjuhh mentioned the best way to do this in code is with a try except, such as:

try:
    import pandas as pd
except ImportError:
    print("You must have pandas installed to run this script")
    exit()

This solves some of your issues, but insuring people have python and pip installed is not something you can handle on your own. I would recommend putting that information into a README file in the project so people are aware, but ultimately it would fall on them to do that part.

But there are some better, and more common python ways to handle the python packages you're using and it has to do with how you are structuring your project. If it is a standalone project (meaning it runs by itself and isn't intended to be imported into another project) a good way is to write a requirements.txt file that contains everything that needs to be installed.

so for example you're requirements.txt file would include:

bs4

and then each new python dependency would go on a new line. From there people just need to type pip install -r requirements.txt, most people familiar with python will know that and for those that aren't you should also include that in the README file.

If you intend to write your own module (code that other people import into their project like bs4), then you should read up on the setup.py system built into python.

Kieran Wood
  • 1,297
  • 8
  • 15