是否可以使用 exec() 运行 缩进块?
Is it possible to run indented blocks using exec()?
使用 exec()
python 命令,是否可以 运行 缩进代码块(如 if/else
语句或 try/except
)。例如:
name = input("Enter name: ")
if name == "Bob":
print("Hi bob")
else:
print("Hi user")
目前我正在使用它来 运行 代码:
code_list = []
while True:
code = input("Enter code or type end: ")
if code == "end":
break
else:
code_list.append(code)
for code_piece in code_list:
exec(code_piece)
我也知道这不是很 "Pythonic" 或 "Good practise" 让用户输入他们自己的代码,但它对我代码的其他部分很有用。
这里的问题不是缩进。问题是您试图 exec
一条一条地复合语句的行。 Python 没有完整的内容就无法理解复合语句。
exec
整个输入作为一个单元:
exec('\n'.join(code_list))
来自 exec() 文档:
This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed ...
因此,您可以执行以下操作
exec("a=2\nb=3")
exec("if a==2:\n\tprint(a)\nelse:\tprint(b)")
您只需要遵循正确的语法和缩进即可。
在 exec() 函数中格式化代码的另一种方法是使用三重引号,这样可以很容易地看到代码的样子。
code = """ # Opening quotes
for i in range(0, 10): # Code line 1
print(i) # Code line 2
""" # Closing quotes
exec(code)
如果您要求用户输入代码,这可能不起作用,但这是一个可能会派上用场的技巧。
使用 exec()
python 命令,是否可以 运行 缩进代码块(如 if/else
语句或 try/except
)。例如:
name = input("Enter name: ")
if name == "Bob":
print("Hi bob")
else:
print("Hi user")
目前我正在使用它来 运行 代码:
code_list = []
while True:
code = input("Enter code or type end: ")
if code == "end":
break
else:
code_list.append(code)
for code_piece in code_list:
exec(code_piece)
我也知道这不是很 "Pythonic" 或 "Good practise" 让用户输入他们自己的代码,但它对我代码的其他部分很有用。
这里的问题不是缩进。问题是您试图 exec
一条一条地复合语句的行。 Python 没有完整的内容就无法理解复合语句。
exec
整个输入作为一个单元:
exec('\n'.join(code_list))
来自 exec() 文档:
This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed ...
因此,您可以执行以下操作
exec("a=2\nb=3")
exec("if a==2:\n\tprint(a)\nelse:\tprint(b)")
您只需要遵循正确的语法和缩进即可。
在 exec() 函数中格式化代码的另一种方法是使用三重引号,这样可以很容易地看到代码的样子。
code = """ # Opening quotes
for i in range(0, 10): # Code line 1
print(i) # Code line 2
""" # Closing quotes
exec(code)
如果您要求用户输入代码,这可能不起作用,但这是一个可能会派上用场的技巧。