zoukankan      html  css  js  c++  java
  • Python可执行对象——exec、eval、compile

    Python提供的调用可执行对象的内建函数进行说明,涉及exec、eval、compile三个函数。exec语句用来执行存储在代码对象、字符串、文件中的Python语句,eval语句用来计算存储在代码对象或字符串中的有效的Python表达式,而compile语句则提供了字节编码的预编译。

    当然,需要注意的是,使用exec和eval一定要注意安全性问题,尤其是网络环境中,可能给予他人执行非法语句的机会。

    1.exec

    格式:exec obj

    obj对象可以是字符串(如单一语句、语句块),文件对象,也可以是已经由compile预编译过的代码对象。

    下面是相应的例子:

    Python可执行对象之exec使用举例

    # 单行语句字符串
    >>> exec "print 'pythoner.com'"
    pythoner.com
     
    #  多行语句字符串
    >>> exec """for i in range(5):
    ...   print "iter time: %d" % i
    ... """
    iter time: 0
    iter time: 1
    iter time: 2
    iter time: 3
    iter time: 4
    

    代码对象的例子放在第3部分一起讲解。

    2.eval

    格式:eval( obj[, globals=globals(), locals=locals()] )

    obj可以是字符串对象或者已经由compile编译过的代码对象。globals和locals是可选的,分别代表了全局和局部名称空间中的对象,其中globals必须是字典,而locals是任意的映射对象。

    下面仍然举例说明:

    Python可执行对象之eval

    >>> x = 7
    >>> eval( '3 * x' )
    21
    

    3.compile

    格式:compile( str, file, type )

    compile语句是从type类型(包括’eval': 配合eval使用,’single': 配合单一语句的exec使用,’exec': 配合多语句的exec使用)中将str里面的语句创建成代码对象。file是代码存放的地方,通常为”。

    compile语句的目的是提供一次性的字节码编译,就不用在以后的每次调用中重新进行编译了。

    还需要注意的是,这里的compile和正则表达式中使用的compile并不相同,尽管用途一样。

    下面是相应的举例说明:

    Python可执行对象之compile

    >>> eval_code = compile( '1+2', '', 'eval')
    >>> eval_code
    <code object <module> at 0142ABF0, file "", line 1>
    >>> eval(eval_code)
    3
     
    >>> single_code = compile( 'print "pythoner.com"', '', 'single' )
    >>> single_code
    <code object <module> at 01C68848, file "", line 1>
    >>> exec(single_code)
    pythoner.com
     
    >>> exec_code = compile( """for i in range(5):
    ...   print "iter time: %d" % i""", '', 'exec' )
    >>> exec_code
    <code object <module> at 01C68968, file "", line 1>
    >>> exec(exec_code)
    iter time: 0
    iter time: 1
    iter time: 2
    iter time: 3
    iter time: 4
    
  • 相关阅读:
    我们可以用JAX-WS轻松实现JAVA平台与其他编程环境(.net等)的互操作
    Eclipse 枚举类报错
    eclipse 遇关键字enum编译问题解决
    接口测试框架开发(二):extentreports报告中文乱码问题
    接口测试框架开发(一):rest-Assured_接口返回数据验证
    使用ant运行testng的testng.xml并且使用testng-results.xsl美化结果
    TestNG简单的学习-TestNG运行
    ExtentReports 结合 TestNg 生成自动化 html 报告 (支持多 suite)
    TestNG+ReportNG+Maven优化测试报告
    IDEA+MAVEN+testNG(reportNG)
  • 原文地址:https://www.cnblogs.com/xxpythonxx/p/12147027.html
Copyright © 2011-2022 走看看