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

Python跨目录导入模块报错求助:ImportError: No module named b

Fixing ImportError When Importing b.py into a.py

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:

  1. Add an empty __init__.py file to /home/user/scripts/ (so Python recognizes it as a package).
  2. Run your script from the directory above scripts (/home/user/) using the -m flag to execute it as a module:
    python -m scripts.python_scripts.a
    
  3. 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):

  1. In a.py, use the relative import syntax to reference the lib folder:
    from ..lib import b
    
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:13:47