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
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
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
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.
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.
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.