Help on built-in function execfile in module __builtin__:


execfile(...)

    execfile(filename[, globals[, locals]])

    

    Read and execute a Python script from a file.

    The globals and locals are dictionaries, defaulting to the current

    globals and locals.  If only globals is given, locals defaults to it.

execfile(filename[, globals[, locals]])

This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration — it reads the file unconditionally and does not create a new module. [1]


The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the globals and locals dictionaries as global and local namespace. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If two separate objects are passed as globals and locals, the code will be executed as if it were embedded in a class definition.


Changed in version 2.4: formerly locals was required to be a dictionary.


If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. The return value is None.


Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. execfile() cannot be used reliably to modify a function’s locals.


中文说明:

可以调用文件来执行,当如果执行文件需要参数时就将参数放在sys.argv中即可


#execfile.py 

import sys 

if __name__ == '__main__': 

        print sys.argv 

        print 'execfile'

        sys.argv = 'appcfg.py update sdblog'.split(); 

        print sys.argv 

        execfile('main.py')

#main.py 

import sys 

def main(): 

        print 'main'

        print sys.argv 

if __name__ == '__main__': 

        main()

执行execfile.py test结果如下:

D:\GAE\dev>execfile.py test 

['D:\\GAE\\dev\\execfile.py', 'test'] 

execfile

['appcfg.py', 'update', 'sdblog'] 

main 

['appcfg.py', 'update', 'sdblog']