1

I have a case where a module may optionally exist. If it doesn't exist, it's OK.

I wrote this:

try:
    import debug_trace
    print "[FEATURE_TEST] ... loaded custom debug traces, from %s" % debug_trace.__file__
except ImportError:
    # The file "debug_trace.py" probably doesn't exist
    pass

then I realised that this is not achieving what I want, because it masks errors in the case where the file exists but it contains errors.

How can I safely import a module, if it exists... but, report errors if it contains them?

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98
  • But I've just tried your code and it's working. What's the error you're getting? – Remi Guan Jan 08 '16 at 10:35
  • What parse error you are referring to?..like syntax error or what?..I'm just trying to understand your point here – Iron Fist Jan 08 '16 at 10:36
  • 2
    I think the distinction is pretty irrelevant, you should not have any files with flat out syntax errors in them in the first place; that's something that needs to be caught by your IDE/text editor/development workflow. It's not something to care about in code. – deceze Jan 08 '16 at 10:39
  • The case here is that the users of this system may supply a debug_trace module on the python path. If they don't supply it, it's not a problem. If they do supply it, but it has python syntax or other errors, then it is a problem. I am trying to ask how to differentiate between these cases. – GreenAsJade Jan 08 '16 at 12:40

1 Answers1

1

Have a look at this

[How to check if a python module exists without importing it

So in your particular case I would combine Thomas' answer and your code

import imp
try:
    imp.find_module('debug_trace')
    found = True
except ImportError:
    print "Module debug_trace not found"
    found = False
    pass

if found:
    try:
        import debug_trace
        print "[FEATURE_TEST] ... loaded custom debug traces, from %s" % debug_trace.__file__
    except ImportError:
        # The file "debug_trace.py" exists but importation fails
        pass
Community
  • 1
  • 1
  • This sounds great. The only problem is it doesn't work. To confirm this, I put a print statement in the module to be imported, then did import module. It printed. Then I replaced the import with the find_module, and it threw ImportError, saying the module didn't exist! The only thing I can think of is that import looks in the current working directory, whearas find_module doesn't? – GreenAsJade Jan 09 '16 at 23:01