Python 2.6.1: checking for imports

I wrote a utility script for some of my Mac OSX colleagues with Python 2.6.1. Since they don't have all the required modules, I have a try-except import clause:

    import argparse
except ImportError:
    print "argparse module missing: Please run 'sudo easy_install argparse'"


I'm sure there are more elegant ways to handle this. Any ideas?


source to share

3 answers

Your best shot is to freeze your Python code with all the required modules and distribute it as binary; it worked for me with Windows and Linux, however on Linux, make sure you have a compatible glibc version

There are some freezing tools for Mac OS X, but I haven't used them. I've only used Windows and Linux tools.

check out this link for more information



This is a common idiom, but you can use setuptools

and pip to automate the installation of dependencies ( example ).



This is actually the best way to do it. The same approach, for example, is used to select different json libraries depending on what is installed on the machine:

    import simplejson as json
except ImportError:
    import json




All Articles