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

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

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:

defhello_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 即使答不对问题也是收获的,哈哈.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值