exec函数介绍
exec函数是Python中的自带函数,与eval相比,有着更大的优越性。例如eval函数只能执行计算数学表达式的结果,exec能执行一句或一段Python代码。
exec函数功能
exec可以完成一些简单的输出、输入工作:
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)]
on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>exec("a=input('>>>')")
>>>12
>>>print(a)
'12'
>>>exec("print('Hello!')")
Hello!
>>>
exec也可以定义函数:
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)]
on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>exec("def test(): print('Hello!')")
>>>test()
Hello!
>>>a='''def t():
... print("Hello!")'''
>>>exec(a)
Hello!
>>>
exec执行txt文件:
#code.txt
def cn(*num):
if num == 1:
return True
elif num > 1 :
return False
else:
return None
print(cn(num=1))
print(cn(num=5))
print(cn(num='1'))
调用:
with open('code.txt','r') as file:
d=file.read()
exec(d)
运行结果:
True
False
None
今天就分享到这里啦!有问题记得在评论区回复!