简体   繁体   中英

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 ). 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.

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. Python can't make sense of a compound statement without the whole thing.

exec the whole input as a single unit:

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

From exec() documentation:

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 ...

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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