views:

1013

answers:

2

Hi, what's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script.

I guess I could check if there's a directory on the system that's created during the installation but I feel like there's a better way. I'm trying to make sure the Skype4Py package is installed, and if not I'll install it.

My ideas of accomplishing the checkage

  • check for a directory in the typical install path
  • try to import the package and if an exception is throw, then install package

Thanks for any help!

A: 

Go option #2. If ImportError is thrown, then the package is not installed (or not in sys.path).

eduffy
+8  A: 

If you mean a python script, just do something like this:

try:
 import mymodule
except ImportError, e:
 pass # module doesn't exist, deal with it.
Christopher
Thanks, much appreciated.
Kevin
Warning: I just had a situation today where the ImportError was thrown within the module itself. This should not happen often, but just be aware that this check is not reliable in all cases.
Koen Bok