Python Code to Fix Import Error Module Not Found Despite Installation
Ready-to-use Python scripts and functions to diagnose and fix import errors when modules are installed but not found.
Python Code to Fix Import Error Module Not Found Despite Installation
Here are practical Python code snippets to diagnose and fix import errors when modules are installed but Python can't find them.
Environment Diagnostic Script #
Use this script to quickly identify environment and path issues:
🐍 Try it yourself
Module Installation Checker #
Check if a specific module is properly installed:
🐍 Try it yourself
Environment Path Fixer #
Add missing paths to resolve import issues:
import sys
import os
def fix_import_paths():
"""Add common missing paths to sys.path"""
# Current directory
current_dir = os.getcwd()
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
print(f"Added current directory: {current_dir}")
# Parent directory
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
print(f"Added parent directory: {parent_dir}")
# Site-packages directory
try:
import site
site_packages = site.getsitepackages()
for path in site_packages:
if path not in sys.path and os.path.exists(path):
sys.path.append(path)
print(f"Added site-packages: {path}")
except:
pass
print("✅ Path fixing complete")
# Use before importing problematic modules
fix_import_paths()
Virtual Environment Detector #
Automatically detect and suggest virtual environment issues:
🐍 Try it yourself
Package Reinstaller Function #
Safely reinstall packages that have import issues:
import subprocess
import sys
def reinstall_package(package_name, force=False):
"""Reinstall a package to fix import issues"""
try:
# Uninstall first
print(f"Removing {package_name}...")
subprocess.run([sys.executable, '-m', 'pip', 'uninstall',
package_name, '-y'], check=True)
# Reinstall
install_cmd = [sys.executable, '-m', 'pip', 'install', package_name]
if force:
install_cmd.append('--force-reinstall')
print(f"Installing {package_name}...")
subprocess.run(install_cmd, check=True)
print(f"✅ Successfully reinstalled {package_name}")
# Test import
try:
__import__(package_name)
print(f"✅ Import test successful")
except ImportError:
print(f"❌ Import still failing after reinstall")
except subprocess.CalledProcessError as e:
print(f"❌ Error during reinstallation: {e}")
except Exception as e:
print(f"❌ Unexpected error: {e}")
# Example usage
# reinstall_package('requests')
Import Error Context Manager #
Use this context manager to handle import errors gracefully:
🐍 Try it yourself
Quick Fix Function #
One-liner function to attempt common fixes:
def quick_import_fix(module_name):
"""Attempt quick fixes for import issues"""
import sys
import os
import subprocess
fixes_attempted = []
# Fix 1: Add current directory to path
if os.getcwd() not in sys.path:
sys.path.insert(0, os.getcwd())
fixes_attempted.append("Added current directory to path")
# Fix 2: Try importing again
try:
__import__(module_name)
print(f"✅ {module_name} imported successfully!")
return True
except ImportError:
pass
# Fix 3: Try pip install
try:
subprocess.run([sys.executable, '-m', 'pip', 'install', module_name],
check=True, capture_output=True)
fixes_attempted.append(f"Installed {module_name} with pip")
# Try import again
__import__(module_name)
print(f"✅ {module_name} imported after installation!")
return True
except:
fixes_attempted.append("Pip installation failed")
print(f"❌ Could not fix import for {module_name}")
print("Fixes attempted:", fixes_attempted)
return False
# Usage: quick_import_fix('module_name')
Usage Tips #
- Run diagnostics first: Use the diagnostic script to understand the issue
- Check virtual environment: Most import errors are environment-related
- Test after each fix: Verify the import works before moving to complex solutions
- Use context managers: Handle import errors gracefully in production code
These code snippets provide immediate solutions for the most common causes of "module not found despite installation" errors in Python.