创建process_files.py文件后Pytest运行报错:ModuleNotFoundError问题排查及替代解决方案咨询
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.pyand scan all import lines. Look for mistakes like:
Fix these by removing the# Wrong - don't include .py suffix! import process_files.py from . import generate_files.py.pyextension, 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__.pycan break the entire subpackage's visibility. - You've added them to all package directories (
/tools,/tools/file_parser,/test). Even empty__init__.pyfiles 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.inifile in your project root with this content:[pytest] pythonpath = . - Or run pytest with the
--rootdirflag temporarily:
This ensures pytest treats your project root as a valid Python package source without environment variable hacks.python -m pytest --rootdir=.
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

