簡體   English   中英

python在函數內調用exec()

[英]python call exec() inside a function

我嘗試使用在另一個函數中調用的 exec 函數來執行字符串代碼。 但是,它不打印任何內容。 在這種情況下如何執行字符串代碼?

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()

您有代碼縮進問題。 嘗試這個:

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

所有問題都是引用字符串的縮進這里是解決方案,

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()

輸出

測試2

測試代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM