Keywords: PyMySQL | Ubuntu | Python Module Import | System Package Management | Environment Configuration
Abstract: This paper provides an in-depth analysis of the 'No module named pymysql' import error encountered when using Python 3.5 on Ubuntu 15.10 systems. By comparing the effectiveness of different installation methods, it focuses on the solution of using the system package manager apt-get to install python3-pymysql, and elaborates on core concepts such as Python module search paths and the differences between system package management and pip installation. The article also includes complete code examples and system configuration verification methods to help developers fundamentally understand and resolve such environment dependency issues.
Problem Background and Environment Analysis
When developing with Python 3.5 on Ubuntu 15.10 64-bit operating systems, many developers encounter a common import error: ImportError: No module named 'pymysql'. This issue is particularly noteworthy because the same Python code runs correctly on Windows systems, indicating that the problem is closely related to environment configuration rather than inherent code defects.
Core Principles of the Solution
Through thorough analysis, the most effective solution involves using Ubuntu's system package manager for installation:
sudo apt-get install python3-pymysql
This command resolves the issue because it ensures the PyMySQL module is installed in the system-level Python 3 package directory. In Linux systems, Python packages managed by the system package manager are typically located in the /usr/lib/python3/dist-packages/ directory, which is included by default in Python's module search path.
Comparative Analysis of Different Installation Methods
Let's understand the differences between various installation methods through specific code examples:
Method 1: System Package Manager Installation (Recommended)
import subprocess
import sys
# Install using system package manager
subprocess.check_call(['sudo', 'apt-get', 'install', '-y', 'python3-pymysql'])
# Verify installation
import pymysql
print(f"PyMySQL version: {pymysql.__version__}")
print(f"Module path: {pymysql.__file__}")
Method 2: Analysis of pip Installation Issues
# Check pip installation package locations
import site
print("User site-packages directory:", site.getusersitepackages())
print("System site-packages directory:", site.getsitepackages())
# Check Python path
import sys
print("Python path:", sys.path)
In-Depth Technical Analysis
The root cause of this problem lies in Python's module search mechanism and the complexity of system environment configuration:
1. Python Module Search Path Mechanism
Python searches multiple directories in a specific order when importing modules:
import sys
# Display complete module search path
for i, path in enumerate(sys.path):
print(f"{i}: {path}")
2. Differences Between System Package Management and pip
Significant differences exist between system package managers (apt-get) and pip in package management:
- Installation Location: apt-get installs packages to system directories, while pip defaults to user directories
- Dependency Management: apt-get handles system-level dependencies
- Permission Requirements: System package installation requires root privileges
Complete Verification Process
To ensure the problem is thoroughly resolved, we recommend executing the following complete verification process:
#!/usr/bin/env python3
import sys
import subprocess
def check_pymysql_installation():
"""Complete function to check PyMySQL installation status"""
# Check Python version
print(f"Python version: {sys.version}")
# Attempt to import PyMySQL
try:
import pymysql
print("✓ PyMySQL import successful")
print(f" Module location: {pymysql.__file__}")
print(f" Version information: {pymysql.__version__}")
return True
except ImportError as e:
print(f"✗ PyMySQL import failed: {e}")
return False
def install_pymysql_system():
"""Install PyMySQL using system package manager"""
try:
print("Installing python3-pymysql via apt-get...")
result = subprocess.run(
['sudo', 'apt-get', 'install', '-y', 'python3-pymysql'],
capture_output=True,
text=True
)
if result.returncode == 0:
print("✓ Installation completed successfully")
return True
else:
print(f"✗ Installation failed: {result.stderr}")
return False
except Exception as e:
print(f"✗ Installation process exception: {e}")
return False
# Execute verification process
if __name__ == "__main__":
if not check_pymysql_installation():
print("Starting PyMySQL installation...")
if install_pymysql_system():
print("Rechecking installation status...")
check_pymysql_installation()
Analysis of Supplementary Solutions
In addition to the primary system package manager solution, other methods are worth analyzing:
Considerations for pip Installation
While sudo pip install PyMySQL might work in some cases, this approach has potential issues:
- May interfere with system package manager dependencies
- Could create conflicts between different Python environments
- Lacks system-level dependency guarantees
Import Statement Correctness Verification
Ensure using the correct import statement import pymysql rather than import PyMySQL, as Python module names are case-sensitive:
# Correct import method
try:
import pymysql
print("Correct import: import pymysql")
except ImportError:
print("import pymysql failed")
# Incorrect import method (may fail due to case sensitivity)
try:
import PyMySQL
print("import PyMySQL successful")
except ImportError:
print("import PyMySQL failed - note case sensitivity")
Summary and Best Practices
Through in-depth analysis of solutions for PyMySQL import issues in Ubuntu systems, we can draw the following important conclusions:
On Debian-based systems (such as Ubuntu), prioritizing system package manager installation for Python packages ensures optimal compatibility and stability. This approach not only resolves current import issues but also provides a better foundation for subsequent system maintenance and upgrades.
For Python development environment configuration, we recommend establishing standardized installation and verification processes, including:
- Clearly distinguishing between system-level and user-level package installations
- Establishing environment verification scripts to ensure correct dependencies
- Considering characteristic differences between operating systems in cross-platform development
By understanding these underlying mechanisms, developers can more effectively diagnose and resolve similar environment configuration problems, improving development efficiency and application portability.