python中exec()函数用法及三种参数,执行字符串py代码
如果python的代码存储在字符串中,就像前端中的HTML代码以字符串的形式来表达,那该怎么运行这样的python代码呢?python提供了一个内置函数exec(),可以用来执行这样的存储在字符串中或文件中的python代码,十分方便,这样的一种设计也让python的编程更加灵活。
exec()函数的参数
在介绍exec()函数的参数之前,先来看一段程序,如下:
>>> exec(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exec() arg 1 must be a string, bytes or code object
>>> exec("This is a test!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
This is a test!
^
SyntaxError: invalid syntax
代码解析
如上代码,将整形数值1作为参数传递给exec()函数,结果python抛出TypeError,并提示exec() arg 1 must be a string, bytes or code object,由此可见,exec()的参数有三种形式,可以当将字符串作为参数传递给exec()函数时,python又抛出SyntaxError,为什么呢?因为这个字符串应当是python代码形式的字符串,具体的可以看下一个实例。现在先说说exec()的三种参数:如下:
- string:python代码形式的字符串,否则会抛出SyntaxError;
- bytes:字节串数据,也应当是python代码形式;
- code object:字节码对象,这个可以参考python的文档
exec()函数实例代码
exec()除了执行字符串代码,也可以执行存储在文件中的python代码,其原理就是将文件中的python代码读出来,然后执行字符串代码:
>>> exec("a=1") #字符串
>>> a
1
>>> exec(b"c=1") #字节串
>>> c
1
>>> exec(b"x") #字节串中的x作为变量,并没有被赋值,会引not defined的NameError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'x' is not defined
def say(): #文件test.txt中的python代码
print(“hello x1y1z1.com”)
say()
>>> with open("/filepath/test.txt", 'r') as f: #通过读取的方式,将文件中的python代码读取成字符串
... t = f.read()
...
>>> exec(t)
hello x1y1z1.com