tags:

views:

2958

answers:

4

Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks

edit: Resolved myself thanks

+4  A: 

The easiest answer is to put the code you are trying to run inside a function like this

(inside your module that you are importing now):

def main():
    # All the code that currently does work goes in here 
    # rather than just in the module

(The module that does the importing)

import your_module #used to do the work

your_module.main() # now does the work (and you can call it multiple times)
# some other code
your_module.main() # do the work again
Tom Leys
A: 

The import statement -- by definition -- only imports once.

You can, if you want, try to use execfile() (or eval()) to execute a separate file more than once.

S.Lott
+5  A: 

You most probably should not use import for what you are trying to do.

Without further information I can only guess, but you should move the code in the module you import from the top level into a function, do the import once and than simply call the function from you loop.

hop
A: 

While Tom Ley's answer is the correct approach, it is possible to import a module more than once, using the reload built-in.

module.py:
print "imported!"

>>> import module
imported!
>>> reload(module)
imported!
<module 'module' from 'module.pyc'>

Note that reload returns the module, allowing you to rebind it if necessary.

Matthew Trevor
Would probably replace reload(module) with module = reload(module), just for clarity.
Ali A
Also, see http://pyunit.sourceforge.net/notes/reloading.html. It's not as simple as it appears.
S.Lott
Ali: I considered that, but the rebinding isn't essential for the reload, as the original binding is affected. I hoped pointing out that it returned the module would be enough.
Matthew Trevor