使用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:
另外执行的命令文件 execfile.py:
执行命令文件就能实现运行外部脚本的功能了。
2.exec()函数:
这个函数可以动态执行python代码,比如 将代码作为字符串数据执行:
3. 作为进程管理的一些函数,可以用来执行外部程序的函数,主要在os模块之中,这个就多了,比较复杂,参考Python的官方文档。
没事多看看stackoverflow 即使答不对问题也是收获的,哈哈.
一开始没能完全理解意思,回答得牛头不对马嘴,不过还是学到了一些东西:
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 即使答不对问题也是收获的,哈哈.
相关文章推荐
- python使用PyV8执行javascript代码示例分享
- 使用Python生成Shell命令,批量执行程序代码解析
- Python 使用 UTF-8 编码,python代码中包含中文时执行脚本错误的解决办法。
- python中使用time模块计算代码执行效率的精度测试(转)
- python使用PyV8执行javascript代码示例分享
- python中使用time模块计算代码执行效率的精度测试
- python调用Java代码并执行--------jpype使用篇
- Python 使用 UTF-8 编码,python代码中包含中文时执行脚本错误的解决办法。
- 在python中执行外部可执行程序,使用subprocess模块
- Python - 使用Pyinstaller将Python代码生成可执行文件
- python入门(5)使用文件编辑器编写代码并保存执行
- 飘逸的python - 使用dis模块进行代码层次的性能剖析
- 使用PYTHON接收多播数据的代码
- 使用C++模板和不使用C++模板两种情况中的执行代码大小近似估计
- 使用OpenCV_python中的DNN调用CaffeModel识别图像只需30行代码
- 使用Perl或者Python加载Praat脚本在DOS命令窗口直接执行
- python基础之使用os.system来执行系统命令
- Spring Boot 启动时执行特殊的代码使用CommandLineRunner、ApplicationRunner
- 黑客走开系列1:Python使用元组做函数实参让代码更安全!
- C#中使用MSScriptControl中执行 javascript代码