5

While importing a python script from another script I want the script code that is classically protected by

if __name__ == "__main__": 
 .... 
 ....

to be run, how can I get that code run?

What I am trying to do is from a python script, dynamically change a module then import an existing script which should see the changes made and run its __main__ code like it was directly invoked by python?

I need to execute the 2nd python script in the same namespace as the 1st python script and pass the 2nd script command line parameters. execfile() suggested below might work but that doesn't take any command line parameters.

I would rather not edit the 2nd script (external code) as I want the 1st script to be a wrapper around it.

asked Jun 22, 2010 at 10:45

1 Answer 1

6

If you can edit the file being imported, one option is to follow the basic principle of putting important code inside of functions.

# Your script.
import foo
foo.main()
# The file being imported.
def main():
 print "running foo.main()"
if __name__ == "__main__":
 main()

If you can't edit the code being imported, execfile does provide a mechanism for passing arguments to the imported code, but this approach would make me nervous. Use with caution.

# Your script.
import sys
import foo
bar = 999
sys.argv = ['blah', 'fubb']
execfile( 'foo.py', globals() )
# The file being exec'd.
if __name__ == "__main__":
 print bar
 print sys.argv
answered Jun 22, 2010 at 11:38
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, and agreed its a good idea in general but in this case the 2nd script is not in my control ...also, I want the solution to work as a wrapper regardless of how the 2nd script was written.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.