Python:检测循环导入的脚本

发布于 2025-01-06 22:33:25 字数 1539 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑凤梨 2025-01-13 22:33:25

我不完全了解任何工具,但我现在可以想到几种方法来获取这些数据。

让解释器为您工作

对于您拥有的每个模块,创建一个导入它的存根模块,然后使用以下命令运行该模块

$ python -v stub_module.py

这仅在您不依赖 sys.path hackery 并且您的模块在导入时不会产生危险的副作用时才有效(这两个功能都很可疑)。您将获得传递导入闭包,但用它检测循环导入应该很简单。

使用 logilab.astng

logilab.astng 一起使用,可以轻松提取模块的所有直接导入(查找logilab.astng.nodes.Fromlogilab.astng.nodes.Import 类型的节点)。获得所有模块的直接导入列表后,创建导入图并查找循环。

同样,只有当您不使用 sys.path hacks 时,这才有效。

I do not know any tool outright, but there are a couple of ways I can think of right now that will get you this data.

Make the Interpreter Work for You

For every module you have, create a stub module that imports it, and then run this module with

$ python -v stub_module.py

This only works if you do not rely on sys.path hackery and your modules do not have dangerous side effects when imported (both very dubious features FWIW). You will get the transitive import closure, but detecting circular imports with this should be straightforward.

Use logilab.astng

With logilab.astng,it is easy to extract all direct imports of your modules (look for nodes of type logilab.astng.nodes.From and logilab.astng.nodes.Import). Once you have the list of direct imports of all modules, create the import graphs and look for cycles.

Again, this only works only if you do not use sys.path hacks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文