您的位置:首页 > 编程语言 > Python开发

使用python代码执行外部的代码

2013-11-29 16:56 543 查看
那天跑到stackoverfow里瞎看,遇到这样一个问题:http://stackoverflow.com/questions/19945161/python-pass-variable-to-import-file/19945501#19945501

一开始没能完全理解意思,回答得牛头不对马嘴,不过还是学到了一些东西:

1.execfile()函数:

帮助文档中是这么定义的,来简单翻译一下

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.

这个函数类似于exec语句,但是解析的是一个文件而非字符串,和import(一开始写成impact了 哈哈 万恶的职业习惯 万恶的crusher...)语句不同,它不使用模块管理,而是无条件地读取文件而不是创建一个新的模块。

还是来实际使用一下:

执行一个外部的脚本文件 hello_world.py:

def hello_world(name):
print 'Hello ', name

hello_world(name) # not a string, just a var


另外执行的命令文件 execfile.py:

execfile('./hello.py', {'name': "jaw-crusher"}) # a dict with the parameters


执行命令文件就能实现运行外部脚本的功能了。

2.exec()函数:

这个函数可以动态执行python代码,比如 将代码作为字符串数据执行:

code = '''print "%s" % ('hello world')'''
exec(code)


3. 作为进程管理的一些函数,可以用来执行外部程序的函数,主要在os模块之中,这个就多了,比较复杂,参考Python的官方文档。

没事多看看stackoverflow 即使答不对问题也是收获的,哈哈.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: