简体   繁体   English

python在函数内调用exec()

[英]python call exec() inside a function

I try to execute string code using exec function which is being called at another function.我尝试使用在另一个函数中调用的 exec 函数来执行字符串代码。 However, it doesn't print anything.但是,它不打印任何内容。 How do I execute string code in this case?在这种情况下如何执行字符串代码?

def test_code():
    print "test_code"

def run():
    try:
        a= '''def test2():
            print "test2"

            test_code()
            test2()'''

        exec(a)
    except Exception as e:
        print e

run()

You have a code indentation issue.您有代码缩进问题。 try this:尝试这个:

def test_code():
    print "test_code"


def run():
    try:
        a= '''
def test2():
    print "test2"

test_code()
test2()
'''

        exec(a)
    except Exception as e:
        print e

run()
# test_code
# test2

All problem is indentation of quoted string Here is solution,所有问题都是引用字符串的缩进这里是解决方案,

def test_code():
    print "test_code"

def run():
    try:
        a= '''
def test2():
    print "test2"
    test_code()
test2()'''

        exec(a)
    except Exception as e:
        print e
run()

Output输出

test2测试2

test_code测试代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM