You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向Python简单项目添加c.py后导入模块时报错‘ModuleNotFoundError: No module named c’的问题求助

解答你的Python包导入问题

Hey there! Let's break down what's going on with your project. First off: your project layout doesn't have an inherent flaw, and yes, it absolutely should work for a simple "hello world" scenario—you just need to tweak how you're importing modules inside the package.

为什么终端报错,但PyCharm能正常运行?

The core issue boils down to how Python resolves imports, and the difference between your terminal's native Python environment and PyCharm's path configuration.

When you run python3 from the outer blah directory and try import blah.a, Python looks for modules in the directories listed in sys.path—which by default includes your current working directory (the outer blah). It finds the inner blah package just fine, but when a.py tries import b or import c, Python searches sys.path for top-level modules named b or c—it doesn't automatically check the same sub-package as a.py.

PyCharm, on the other hand, automatically configures your project's path to simplify package imports. It adds your project root to sys.path and recognizes the inner blah as a proper package, so it implicitly handles the intra-package imports that work in the IDE but fail in the terminal.

怎么修复终端里的报错?

You have two standard, Pythonic ways to fix this:

1. 使用相对导入(推荐用于包内模块间的导入)

Modify the imports in a.py to use relative paths, which tell Python to look for modules in the same package:

from . import b
from . import c
# Do your stuff here

The . refers to the current package (the inner blah), so Python will correctly find b.py and c.py alongside a.py.

2. 使用完整的绝对导入

Alternatively, you can use the full package path to import b and c, which works regardless of where you run the code (as long as the outer blah is in sys.path):

from blah import b, c
# Or
import blah.b
import blah.c

This explicitly tells Python to look inside the blah package for the modules.

小提示:完善你的包结构

While Python 3.3+ supports namespace packages without an __init__.py file, it's still a good practice to add an empty __init__.py file inside the inner blah directory. This makes it clear to Python (and other developers) that the directory is intended to be a Python package.

Once you adjust your imports, your simple "hello world" setup should run perfectly in both the terminal and PyCharm.

内容的提问来源于stack exchange,提问作者blah deBlah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:24:05