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()
source share