zoukankan      html  css  js  c++  java
  • 使用python代码执行外部的代码

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

  • 相关阅读:
    【Python第九篇】异步IO数据库队列缓存
    【Python第八篇】线程、进程及协程
    【Python第七篇】Socket网络编程
    实验五全部代码,ajax请求
    添加员工
    联级选择
    查询,利用jquery选择器
    列表、表格单选框
    注册
    聊天框
  • 原文地址:https://www.cnblogs.com/jaw-crusher/p/3449927.html
Copyright © 2011-2022 走看看