个人博客转至:tybai.com

无聊就想打码,打码使我快乐


Fork me on GitHub

python预编译函数compile,exec,eval

funcname = "func"
func = "def %s():\n" % 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():\n" % 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():\n" % funcname
funccontent = '    print "hello,world"'
func += funccontent
evalcode = compile(func, '', 'exec')
exec (evalcode)
eval("%s" % funcname)

运行成功

posted on 2017-03-21 15:01  TTyb  阅读(300)  评论(0编辑  收藏  举报

导航


不用多久

我就会升职加薪

当上总经理

出任CEO

迎娶白富美

走上人生巅峰

Pulpit rock