Check if module is installed

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kless

    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

    #2
    Re: Check if module is installed

    On Aug 4, 2:25 pm, Kless <jonas....@goog lemail.comwrote :
    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

    Comment

    • Steven D'Aprano

      #3
      Re: Check if module is installed

      On Mon, 04 Aug 2008 05:25:08 -0700, Kless wrote:
      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='pinin g for the fjords'):
      return "It's not dead, it's %s." % s


      --
      Steven

      Comment

      Working...