[英]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.