前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python内置函数4-execfile

python内置函数4-execfile

作者头像
py3study
发布2020-01-09 16:47:10
5170
发布2020-01-09 16:47:10
举报
文章被收录于专栏:python3python3

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']

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档