今日已更新 223 条资讯 | 累计 41900 条内容
关于我们

What are PyInstaller "hidden imports" — and why do only dynamic imports break?

Susumu Takahashi 2026年09月11日 08:21 1 次阅读 来源:Dev.to

If you've ever packaged a Python desktop app with PyInstaller, you may have run into this: the app runs perfectly from source, but the frozen executable throws ModuleNotFoundError — and only when you exercise one particular feature. It doesn't crash on startup. It crashes three clicks deep, in a code path nobody happened to test right after the build. This post breaks down why that happens and what "hidden imports" actually means. Note: PyInstaller is a tool that bundles a Python script together with its dependencies into a single platform-specific executable (a .exe on Windows, or a binary embedded in a .app on macOS), so end users don't need a Python environment installed to run it. PyInstaller inspects what the code looks like, not what it does PyInstaller doesn't execute your script to figure out its dependencies. It statically reads the entry-point file's source, walks import and from ... import ... statements, and builds a dependency graph from that. Crucially, none of your code actually runs during this phase — it's purely a textual scan of what modules are referenced in the source. This approach works fine as long as module references are written as plain, literal import statements. Trouble starts when a module name is only determined at runtime . The common patterns behind hidden imports PyInstaller's own documentation uses the term "hidden import" for exactly this class of problem, and it generally falls into a few patterns: Dynamically constructed import strings — code like importlib.import_module(f"core.{plugin_name}") , where the module name is assembled from a runtime variable. At analysis time, there's no way to know what plugin_name will be, so the module never appears in the dependency graph at all. Plugin-style discovery — patterns using something like pkgutil.iter_modules() to scan a directory at runtime and import whatever it finds. No individual module name is ever written literally in the source, so static analysis has nothing to latch onto. Dy

本文内容来源于互联网,版权归原作者所有
查看原文