• 内置函数——eval、exec、compile


    eval() 将字符串类型的代码执行并返回结果

    print(eval('1+2+3+4'))

    exec()将自字符串类型的代码执行

    print(exec("1+2+3+4"))
    exec("print('hello,world')")
    code = '''
    import os 
    print(os.path.abspath('.'))
    '''
    code = '''
    print(123)
    a = 20
    print(a)
    '''
    a = 10
    exec(code,{'print':print},)
    print(a)
    指定global参数

    compile  将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。

    参数说明:   

    1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  

    2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  

    3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。

    复制代码
    >>> #流程语句使用exec
    >>> code1 = 'for i in range(0,10): print (i)'
    >>> compile1 = compile(code1,'','exec')
    >>> exec (compile1)
    1
    3
    5
    7
    9
    

    >>> #简单求值表达式用eval
    >>> code2 = '1 + 2 + 3 + 4'
    >>> compile2 = compile(code2,'','eval')
    >>> eval(compile2)

    >>> #交互语句用single
    >>> code3 = 'name = input("please input your name:")'
    >>> compile3 = compile(code3,'','single')
    >>> name #执行前name变量不存在
    Traceback (most recent call last):
    File
    "<pyshell#29>", line 1, in <module>
    name
    NameError: name
    'name' is not defined
    >>> exec(compile3) #执行时显示交互命令,提示输入
    please input your name:'pythoner'
    >>> name #执行后name变量有值
    "'pythoner'"

    复制代码
  • 相关阅读:
    scss使用指南--每天一点
    Egret引擎开发基础(一)
    vue-awesome-swiper使用自动轮播和循环轮播不生效(loop和autoplay)
    Vue项目中title的设置,使用document.title返回时不生效
    charles系列破解激活注册码
    Vscode中vue项目中无法对js进行提示
    JS数组与对象的遍历方法大全
    手把手教你用webpack3搭建react项目(开发环境和生产环境)(二)
    服务器安装redis-stat和easyNmon
    Shell备份数据库
  • 原文地址:https://www.cnblogs.com/l-hf/p/11532317.html
Copyright © 2020-2023  润新知