2

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

2
  • 1
    Can you provide a short example of what you're trying to do, and what you expect to happen? Commented Nov 9, 2008 at 23:42
  • 2
    @Clinton: please update the question with the answer you found, or write an answer to do so, for the benefit of others. Commented Nov 10, 2008 at 0:38

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

1

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.

Comments

1

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.

3 Comments

Would probably replace reload(module) with module = reload(module), just for clarity.
Also, see pyunit.sourceforge.net/notes/reloading.html. It's not as simple as it appears.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.