Python2.7+pytest导入报错:No module named,常规方案无效求助
ImportError: No module named in Python 2.7 + pytest I’ve helped troubleshoot this exact issue with Python 2.7 and pytest before—this combo has some path-specific quirks that make standard fixes less reliable. Let’s walk through targeted solutions that should work for your setup:
First, Confirm Your Project Structure
Make sure your repo follows this common layout (critical for imports to work):
repo-root/ ├── myapp/ │ ├── __init__.py # Required for Python 2.7 to treat this as a package │ └── myapplib.py └── tests/ ├── __init__.py # Also required here └── test_stuff.py
If you’re missing any __init__.py files, add them (they can be empty)—Python 2.7 won’t recognize directories as importable packages without them.
Solution 1: Update sys.path Directly in Your Test File
Add this code at the very top of tests/test_stuff.py before any other imports:
import sys import os # Add the repo root to Python's path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # Now you can import your module normally from myapp import myapplib
This explicitly tells Python where to find your myapp package, bypassing any path confusion from pytest’s default behavior.
Solution 2: Set PYTHONPATH Before Running pytest
Instead of modifying test files, set the environment variable to point to your repo root before executing pytest:
Linux/macOS (Terminal)
export PYTHONPATH=$(pwd) pytest tests/test_stuff.py
Windows (Command Prompt)
set PYTHONPATH=%cd% pytest tests/test_stuff.py
Windows (PowerShell)
$env:PYTHONPATH = Get-Location pytest tests/test_stuff.py
This makes your myapp package available globally to pytest without modifying code.
Critical Pitfalls to Avoid
- Don’t use relative imports (e.g.,
from ..myapp import myapplib) in test files—Python 2.7’s relative import system doesn’t play well with pytest’s test runner. - Avoid naming conflicts: Make sure none of your modules or packages share names with Python standard library modules (e.g., don’t name a file
logging.py). - Always run pytest from the repo root: Even with the fixes above, running from subdirectories can introduce path issues.
内容的提问来源于stack exchange,提问作者brandonscript

