|  | Check if module is installed |  | |
| | | Kless |  |
| Posted: Mon Aug 04, 2008 12:25 pm Post subject: Check if module is installed |  |
How to check is a library/module is installed on the system? I use the next code but it's possivle that there is a best way.
------------------- try: import foo foo_loaded = True except ImportError: foo_loaded = False -------------------
Thanks in advance! |
| |
| | | Chris Ortner |  |
| Posted: Mon Aug 04, 2008 12:57 pm Post subject: Re: Check if module is installed |  |
On Aug 4, 2:25 pm, Kless <jonas....@googlemail.com> wrote:
| Quote: | try: import foo foo_loaded = True except ImportError: foo_loaded = False
|
Many projects use this as the standard procedure to check a module's presence. I assume, this is the best way.
Chris |
| |
| | | Steven D'Aprano |  |
| Posted: Mon Aug 04, 2008 9:12 pm Post subject: Re: Check if module is installed |  |
| |  | |
On Mon, 04 Aug 2008 05:25:08 -0700, Kless wrote:
| Quote: | How to check is a library/module is installed on the system? I use the next code but it's possivle that there is a best way.
------------------- try: import foo foo_loaded = True except ImportError: foo_loaded = False -------------------
|
The "best" way depends on what you expect to do if the module can't be imported. What's the purpose of foo_loaded? If you want to know whether foo exists, then you can do this:
try: foo except NameError: print "foo doesn't exist"
Alternatively:
try: import foo except ImportError: foo = None x = "something" if foo: y = foo.function(x)
If the module is required, and you can't do without it, then just fail gracefully when it's not available:
import foo # fails gracefully with a traceback
Since you can't continue without foo, you might as well not even try. If you need something more complicated:
try: import foo except ImportError: log(module not found) print "FAIL!!!" sys.exit(1) # any other exception is an unexpected error and # will fail with a traceback
Here's a related technique:
try: from module import parrot # fast version except ImportError: # fallback to slow version def parrot(s='pining for the fjords'): return "It's not dead, it's %s." % s
-- Steven |
| |
| | | Wojtek Walczak |  |
| Posted: Mon Aug 04, 2008 9:54 pm Post subject: Re: Check if module is installed |  |
Dnia Mon, 4 Aug 2008 05:25:08 -0700 (PDT), Kless napisa³(a):
| Quote: | How to check is a library/module is installed on the system? I use the next code but it's possivle that there is a best way.
|
You may also be interested in techniques to keep your software compatible with older versions of python. Take a look at this example: LINK
-- Regards, Wojtek Walczak, LINK |
| |
|
|