我尝试使用在另一个函数中调用的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()
答案 0 :(得分:1)
您有代码缩进问题。试试这个:
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
答案 1 :(得分:0)
所有问题都是引用字符串的缩进 这是解决方案,
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()
输出
TEST2
test_code