我正在创建一个无限循环问题(只是为了好玩),但我遇到了这个错误:“RecursionError:酸洗对象时超出了最大递归深度”以下消息:
Traceback (most recent call last):
File "<pyshell#34>", line 2, in <module>
exec(p.read())
File "<string>", line 6, in <module>
File "<string>", line 6, in <module>
File "<string>", line 6, in <module>
[Previous line repeated 503 more times]
File "<string>", line 4, in <module>
RecursionError: maximum recursion depth exceeded while pickling an object
我没有导入pickling模块,不知道为什么会出现这个错误。
我在 Python 解释器中运行了这段代码:
with open("Cool.py", "a")as p1:
p1.write("""for _ in range(10):\n\t""")
p1.write("""with open("Cool.py" "r")as p1:\n""")
p1.write("""\t\tfor b in p1:\n""")
p1.write("""\t\t\tprint(b)""")
我的文档文件夹中已经有一个名为“Cool.py”的空 .py 文件(我是 Mac 用户)。 运行上述代码后,我运行此代码来调用该文件,而无需打开它:
with open("Cool.py") as p:
exec(p.read())
我知道它很懒,但我主要只是好奇为什么它会提出 pickle 模块。 任何人都可以解释为什么我收到错误(以及如何修复它 - 尽管这不太重要)。
使用前五行代码,它会打开文件
cool.py
并写入以下内容。
**#assume this is code_1**
for _ in range(10):
with open("Cool.py", "r")as p1:
for b in p1:
print(b)
现在您正在执行以下代码行:
**#Assume this is code_2**
with open("Cool.py") as p:
exec(p.read())
使用代码
exec(p.read())
,您要求执行读取的代码。
也就是说 code_1 将作为 python 代码执行(请参阅我的评论了解什么是 code_1)。在这里,您要求打开同一个文件十次。但是,事情还没有结束。
每次打开文件时,code_2都会原样执行文件中的code_1
with open
(隐藏含义:如果打开了,则执行里面的代码。)并且每次需要打开同一个文件10次,并且每次打开时都会执行代码。这是一个永无止境的过程。
虽然
with open
的目的是为了避免每次都关闭失败,但这就是它的行为方式。
减少复杂性的更好方法是:编写一段代码,在文件中写入一个函数。导入它并运行该函数。