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)

运行成功

原文地址:https://www.cnblogs.com/TTyb/p/6594388.html