-2

I started writing python codes two weeks ago and until now I have manipulated some excel data after converting it to txt file. Now, I want to manipulate excel data directly, so I need to install openpyxl package. However, my script will be used in many different places and computers (Note that: all of them use either OS X or a Linux distrubution) which might (probably do not) contain openpyxl package installed. I want my script to check whether this package exist, and if it does not exit, then download and install it.

For that purpose, as I searched and found that I could check the existence of the package by first importing the pip module and then pip.get_installed_distributions() method. However, I am not sure whether I am in a wrong way or not. Besides, I have no idea how to download and install openpyxl package "without leaving the script".

Would you like to help me ?

Charlie Clark
  • 18,477
  • 4
  • 49
  • 55
kimimki
  • 65
  • 1
  • 7
  • See [How do I automatically install missing python modules?](http://stackoverflow.com/questions/6120902/how-do-i-automatically-install-missing-python-modules) – Ryan D.W. Feb 26 '16 at 19:32

1 Answers1

2

You are getting ahead of yourself by trying to solve a deployment problem when you don't have the software to deploy.

Having a script trying to manage its own deployment is generally a bad idea because it takes responsibility away from package managers.

Here is my answer to your question:

  1. Build your software under the assumption that all packages are installed/deployed correctly. I recommend creating a virtualenv (virtual environment) on your development computer, using pip to install openpyxl and any other packages you need.
  2. Once your software is built and functional, read up on how to deploy your software package to PyPi: https://pypi.python.org/pypi. Create your package by defining openpyxl as a dependency, ensure your package can be installed/run properly (I recommend adding in tests), then deploy to PyPi so anyone can use your software.

If you want to add a nice layer of validation in your script just in case, add the following to your main method:

#!/usr/bin/env python3
import sys
try:
    import openpyxl
except ImportError as iE:
    print("Python Excel module 'openpyxl' not found")
    sys.exit(1)

... rest of script ...
NuclearPeon
  • 5,743
  • 4
  • 44
  • 52
  • I forgot to clarify in my answer... the hashbang `#!/usr/bin/env python3` is something that goes at the top of the script **file**, not in a method, so omit that line if you are putting the code in a function. – NuclearPeon Feb 26 '16 at 20:29