Python equivalent to PHP include

include, php, python

Solution

Try `import`, with a try/except on `ImportError`:

try:
    import modulename
except ImportError:
    print 'importing modulename failed'

Without catching `ImportError` it is the equivalent of `require`, sorta-kinda.

Do note that python will only execute the module code once (making this more a `include_once` or `require_once` statement. Functions in the module can be called more than once, of course.

Problem

I need a Python equivalent of PHP's include function. I know of execfile(), but that doesn't work the same. Any ideas?

Original source