How to run a Python script from another script and get the resulting global dict?

Let's say you have a line containing the path to the Python script, and you want to transparently load and execute this script (so there are no fundamental differences for the internal script compared to running it directly through the "python path"). And then get the resulting global dict. I thought runpy.run_path () does this, but there are two problems. If the path contains some Unicode character, then it does not work (see http://bugs.python.org/issue17588 ). And most importantly, given that the global dict is just a copy of the original, as this original is cleared when the temporary module object collects garbage. Thus, the function object is damaged by __globals__ dict (see http://bugs.python.org/issue18331 ).

Do you have any ideas on how to run an internal script?

Update: see my current approach - http://bpaste.net/show/RzAbQxLNXiJsXYm2fplz/ . Any suggestions? Improvements? For example, about the details of what may differ from the point of view of the running script. I know about the problem with loading __main __.

+6
source share
1 answer

Importing a module executes the code at the top level, and this global module namespace is imported as the module name

james@bodacious :~$cat test.py def func(): pass myname = "michael caine" print "hello, %s" % myname james@bodacious :~$python Python 2.7.5 (default, Jul 12 2013, 18:42:21) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import test hello, michael caine >>> dir(test) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'func', 'myname'] >>> 

if the code you want to run is at the top level of the file, simply importing the module will execute the code and give you access to its "global" namespace in just one convenient package. If the code you want to run is not at the top level (for example, if it is in the main() function, which runs only with the common trick if __name__=="__main__" ), you can call this function yourself:

 james@bodacious :~$cat test.py def main(): print "hello there!" if __name__=="__main__": main() james@bodacious :~$python Python 2.7.5 (default, Jul 12 2013, 18:42:21) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import test >>> test.main() hello there! >>> 

Of course, it is possible that the file you want to import is not in sys.path, so it cannot be simply loaded with import . A simplified solution might be to manipulate sys.path , but How to import a module with a full path? describes the best solutions using imp.load_source()

+1
source

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


All Articles