Python跨目录导入模块报错求助:ImportError: No module named b
First, let's confirm your directory structure to align on the setup:
/home/user/scripts/ ├── python_scripts/ │ ├── __init__.py │ └── a.py └── lib/ ├── __init__.py └── b.py
The core issue here is that when you run a.py, Python only checks directories in its sys.path list by default—this includes the folder where a.py lives (/home/user/scripts/python_scripts/), but not the parent directory containing lib. Adding __init__.py marks the folders as packages, but you still need to tell Python where to find the lib package.
Here are three practical ways to resolve this:
Solution 1: Add the parent directory to sys.path (quickest fix)
In a.py, explicitly add the path to the /home/user/scripts/ directory (which holds both python_scripts and lib) to Python's module search path. Using os.path makes this portable, so you don't have to hardcode absolute paths:
import os import sys # Get the parent directory of python_scripts (i.e., /home/user/scripts/) parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(parent_dir) # Now you can import b from lib from lib import b
Solution 2: Use absolute imports with the parent as a package
If you want to treat /home/user/scripts/ as a top-level package:
- Add an empty
__init__.pyfile to/home/user/scripts/(so Python recognizes it as a package). - Run your script from the directory above
scripts(/home/user/) using the-mflag to execute it as a module:python -m scripts.python_scripts.a - In
a.py, use the full absolute import path:from scripts.lib import b
Solution 3: Use relative imports (for package-based execution)
Relative imports work when your code is run as part of a package (not as a standalone script):
- In
a.py, use the relative import syntax to reference thelibfolder:from ..lib import b - Run the script from
/home/user/scripts/with:python -m python_scripts.a
Note: This won't work if you run a.py directly (like python a.py from the python_scripts folder)—relative imports require the script to be executed as part of a package.
内容的提问来源于stack exchange,提问作者Learner

