Python spyder调试因循环导入而冻结 [英] Python spyder debug freezes with circular importing

查看:93
本文介绍了Python spyder调试因循环导入而冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的代码中的某些模块相互调用时,调试器出现问题.实际示例:

I have a problem with the debugger when some modules in my code call each other. Practical example:

文件dog.py包含以下代码:

A file dog.py contains the following code:

import cat
print("Dog")

文件cat.py如下:

The file cat.py is the following:

import dog
print("Cat")

当我运行dog.py(或cat.py)时,我没有任何问题,程序运行平稳.但是,当我尝试对其进行调试时,整个spyder都会冻结,因此我必须终止该程序.

When I run dog.py (or cat.py) I don't have any problem and the program runs smoothly. However, when I try to debug it, the whole spyder freezes and I have to kill the program.

您知道我该如何解决吗?我想使用这种循环导入,因为这些模块使用其他模块中的功能.

Do you know how can I fix this? I would like to use this circular importing, as the modules use functions that are in the other modules.

谢谢!

推荐答案

当我运行dog.py(或cat.py)时,我没有任何问题,程序运行平稳.

When I run dog.py (or cat.py) I don't have any problem and the program runs smoothly.

AFAICT主要是因为脚本是以特殊名称("__ main __" )导入的,而模块是以其自己的名称(此处为"dog"或"cat")导入的.注意:脚本和模块之间的唯一区别是实际加载的-将参数传递给python运行时( python dog.py )或从脚本或任何具有 import <的模块中导入/code>语句.

AFAICT that's mostly because a script is imported under the special name ("__main__"), while a module is imported under it's own name (here "dog" or "cat"). NB : the only difference between a script and a module is actually loaded - passed an argument to the python runtime (python dog.py) or imported from a script or any module with an import statement.

(实际上,循环进口的问题比我上面描述的要复杂一些,但是我将留给知识渊博的人.)

长话短说:除了这个特殊的用例(实际上更多是副作用)之外,Python 不支持循环导入.如果您具有其他脚本或模块共享的函数(类,无论如何),请将这些函数放在另一个模块中.或者,如果您发现两个模块确实相互依赖,则可能只想将它们重新组合到一个模块中(或在一个模块中将相互依赖的部分重新组合,而在一个或多个其他模块中将所有其他部分重新组合).

To make a long story short: except for this particular use case (which is actually more of a side effect), Python does not support circular imports. If you have functions (classes, whatever) shared by other scripts or modules, put these functions in a different module. Or if you find out that two modules really depends on each other, you may just want to regroup them into a single module (or regroup the parts that depend on each other in a same module and everything else in one or more other modules).

此外:除非它是一个简单的单机实用程序或仅依赖于stdlib的东西,否则脚本的内容通常可以更好地简化为 main 函数,用于解析命令行参数/读取配置文件/无论如何,导入所需的模块并开始有效的过程.

Also: unless it's a trivial one-shot util or something that only depends on the stdlib, your script's content is often better reduced to a main function parsing command-line arguments / reading config files / whatever, importing the required modules and starting the effective process.

这篇关于Python spyder调试因循环导入而冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆