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.
The point of having the if __name__ == "__main__" block is to get the piece of code under the condition to get executed when the script is in the __main__ scope. While creating packages in Python, however, it's better if the code to be executed under the __main__ context is written in a separate file.
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
__import__() . This means all semantics of the function are derived from importlib. __import__() . The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg. mod ), while __import__() returns the top-level package or module (e.g. pkg ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With