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

创建process_files.py文件后Pytest运行报错:ModuleNotFoundError问题排查及替代解决方案咨询

Troubleshooting ModuleNotFoundError After Adding process_files.py

Let's break down why this error pops up even though your test doesn't directly import process_files.py, and walk through actionable fixes beyond manually setting PYTHONPATH:

1. First, Check for Import Errors Inside process_files.py

This is the most likely culprit. Even if your test doesn't import process_files.py directly, if another module in your project (like generate_files.py or conftest.py) indirectly imports it, any invalid import statements inside process_files.py will trigger a ModuleNotFoundError during module loading.

  • Open process_files.py and scan all import lines. Look for mistakes like:
    # Wrong - don't include .py suffix!
    import process_files.py
    from . import generate_files.py
    
    Fix these by removing the .py extension, e.g.:
    # Correct relative import
    from . import generate_files
    # Or correct absolute import
    from tools.file_parser import generate_files
    

2. Validate Your init.py Files

While you've added __init__.py files, double-check:

  • They're empty or contain valid code. A broken import in tools/file_parser/__init__.py can break the entire subpackage's visibility.
  • You've added them to all package directories (/tools, /tools/file_parser, /test). Even empty __init__.py files work to mark directories as Python packages in most cases.

3. Configure pytest to Recognize Your Project Root

Instead of manually setting PYTHONPATH, you can tell pytest to include your project root in the Python path permanently:

  • Create a pytest.ini file in your project root with this content:
    [pytest]
    pythonpath = .
    
  • Or run pytest with the --rootdir flag temporarily:
    python -m pytest --rootdir=.
    
    This ensures pytest treats your project root as a valid Python package source without environment variable hacks.

4. Audit conftest.py for Indirect Imports

Your root conftest.py might be importing modules that pull in process_files.py without you realizing it. For example, if you have a line like:

from tools.file_parser import *

This would import all modules in the file_parser subpackage, including process_files.py, and surface any errors in it. Comment out or fix such imports if they're unnecessary.

5. Use Relative Imports Within the Subpackage

If process_files.py needs to import other modules in the same file_parser directory, stick to relative imports to avoid path confusion:

# Inside process_files.py
from . import generate_files  # Imports from the same directory

This is more robust than absolute imports when working within a subpackage.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:37:29