是否可以在交互式 python 中测试方法并在其中保留空行?
def f1():
import random
import time
time.sleep(random.randint(1, 4))
这给出了熟悉的错误
IndentationError: unexpected indent
所以,是的,一种解决方法是删除函数内的所有空行。我想知道这是否真的必须能够在交互模式/REPL 下运行。
谢谢
是否可以在交互式 python 中测试方法并在其中保留空行?
def f1():
import random
import time
time.sleep(random.randint(1, 4))
这给出了熟悉的错误
IndentationError: unexpected indent
所以,是的,一种解决方法是删除函数内的所有空行。我想知道这是否真的必须能够在交互模式/REPL 下运行。
谢谢
可能没有太大帮助,但如果空行缩进,它会起作用。为清楚起见显示的点:
def f1():
....import random
....import time
....
....time.sleep(random.randint(1, 4))
一种选择,特别是对于将代码复制粘贴到交互式解释器中,是将其嵌入原始字符串文字中,并且exec
它:
exec(r'''
def f1():
import random
import time
time.sleep(random.randint(1, 4))''')
如果您输入的代码已经使用'''
字符串,请用r"""..."""
引号将其括起来。如果它已经同时使用'''
and """
,这将不起作用。