• python预编译函数compile,exec,eval


    funcname = "func"
    func = "def %s():
    " % funcname
    funccontent = 'print "hello,world"'
    func += funccontent
    evalcode = compile(func, '', 'eval')
    exec (evalcode)
    eval("%s" % funcname)
    

    执行后编译错误:

    eval_code = compile(func, '', 'eval')
      File "", line 1
        def func():
          ^
    SyntaxError: invalid syntax
    

    报错后使用 exec

    funcname = "func"
    func = "def %s():
    " % funcname
    funccontent = 'print "hello,world"'
    func += funccontent
    evalcode = compile(func, '', 'exec')
    exec (evalcode)
    eval("%s" % funcname)
    

    执行后编译错误:

    Traceback (most recent call last):
      File "/tmp/417881432/main.py", line 5, in <module>
        evalcode = compile(func, '', 'exec')
      File "", line 2
        print "hello,world"
            ^
    IndentationError: expected an indented block
    
    exit status 1
    

    修改缩进

    funcname = "func"
    func = "def %s():
    " % funcname
    funccontent = '    print "hello,world"'
    func += funccontent
    evalcode = compile(func, '', 'exec')
    exec (evalcode)
    eval("%s" % funcname)
    

    运行成功

  • 相关阅读:
    ubuntu 10.04 install network bcm4418
    linux vi commend
    api
    ubuntu安装jdk
    maven常用命令介绍
    ubuntu 10.04 install oracle11g
    putty中文乱码问题解决
    SCP不需要密码
    java command
    Ubuntu vsftpd 安装配置
  • 原文地址:https://www.cnblogs.com/TTyb/p/6594388.html
Copyright © 2020-2023  润新知