简体   繁体   English

是否可以使用exec()运行缩进块?

[英]Is it possible to run indented blocks using exec()?

Using the exec() python command, is it possible to run indented blocks of code (Like if/else statements or try/except ). 使用exec() python命令,可以运行缩进的代码块(如if/else语句或try/except )。 For example: 例如:

name = input("Enter name: ")
if name == "Bob":
     print("Hi bob")
else:
     print("Hi user")

At the moment I am using this to run the code: 目前,我正在使用它来运行代码:

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)

Also I know that this isn't very "Pythonic" or "Good practise" to let the user input their own code but it will be useful in other parts of my code. 我也知道这不是让用户输入自己的代码的“ Python风格”或“良好实践”,但这对我代码的其他部分很有用。

The problem here isn't the indentation. 这里的问题不是缩进。 The problem is that you're trying to exec the lines of a compound statement one by one. 问题是您要一一exec复合语句的各行。 Python can't make sense of a compound statement without the whole thing. 没有完整的内容,Python无法理解复合语句。

exec the whole input as a single unit: exec整个输入作为单个单元:

exec('\n'.join(code_list))

From exec() documentation: exec()文档中:

This function supports dynamic execution of Python code. 此功能支持动态执行Python代码。 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 ... 如果是字符串,则将字符串解析为一组Python语句,然后将其执行...

Thus, you can do things like 因此,您可以做类似的事情

exec("a=2\nb=3")
exec("if a==2:\n\tprint(a)\nelse:\tprint(b)")

You just need to follow the right syntax and indentation. 您只需要遵循正确的语法和缩进即可。

Another way of formatting code within an exec() function is to use triple quotes, which makes it easy to see what the code looks like. 在exec()函数中格式化代码的另一种方法是使用三引号,这使查看代码的外观变得容易。

code = """                     # Opening quotes
for i in range(0, 10):         # Code line 1         
    print(i)                   # Code line 2
"""                            # Closing quotes
exec(code)

This would maybe not work if you're asking the user to input the code, but it's a trick that may come in handy. 如果您要求用户输入代码,这可能行不通,但这可能会派上用场。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM