http://www.python.org/dev/peps/pep-0366/
http://www.python.org/dev/peps/pep-0338/
The runpy module is used to locate and run Python modules without importing them first. Its main use is to implement the -m command line switch that allows scripts to be located using the Python module namespace rather than the filesystem.
runpy模組用於:在不import python模組時,定位並執行該模組。主要用途在於實現命令列-m執行python 模組得效果,但是是在指令碼中而不是檔案系統上。
runpy一個就兩個函數:
runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)
運行指定模組代碼並返回模組得全域字典。
例子:
import runpyfrom pprint import pprintttt = runpy.run_module('classproperty', alter_sys=True)pprint(ttt)
runpy.run_path(file_path, init_globals=None, run_name=None)
執行指定指令檔並返回模組全域字典。
例子:
首先寫一個指令碼
$ cat a.py print 'iiiiiiiiiiiiinnnnnnnnnnnnnn a %s'%bbprint __name__print __file__print __loader__print __package__if __name__ == '__main__': print 'in __main__'
然後
import runpyfrom pprint import pprintbb = 'uuu'ggg = runpy.run_path('a.py', init_globals={'bb':bb}, run_name='__main__')print '====================='pprint( ggg)
init_globals是傳給運行module(檔案)的字典,有四個全域變數是一定會傳過去得:__name__, __file__, __loader__ and __package__