Python dynamically imports the script, the code __name__ == "__main__" must be called

When importing a python script from another script, I need script code that is classically protected

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

how can i run this code?

I am trying to do this with a python script, dynamically change a module, and then import an existing script that should see the changes made and run my code __main__, how was this called directly by python?

I need to execute the second python script in the same namespace as the first python script and pass the command line parameters of the 2nd script. execfile () suggested below may work, but does not accept any command line options.

I would prefer not to edit the second script (external code) as I want the first script to be a wrapper around it.

+3
source share
1 answer

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

# Your script.
import foo

foo.main()

# The file being imported.
def main():
    print "running foo.main()"

if __name__ == "__main__":
    main()

If you cannot edit the imported code, it execfileprovides 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
+5
source

Source: https://habr.com/ru/post/1751181/


All Articles