关于Python内置sqlite3模块依赖机制及Ubuntu环境下链接状态检测的技术问询
Great question! Let's break this down, using Python 3.5 on Ubuntu as an example (the logic applies to newer Python versions too).
First, let's clarify the default behavior: Ubuntu's official Python packages (like the 3.5 version you mentioned) dynamically link the system-wide libsqlite3.so shared library for the _sqlite3 extension module. But custom-compiled Python builds might statically link SQLite instead—so here are reliable ways to verify which one your setup uses:
Method 1: Check shared library dependencies with ldd
The most straightforward way is to inspect the _sqlite3 shared object directly using the ldd command, which lists dynamic dependencies.
Run this in your terminal:
ldd /usr/lib/python3.5/lib-dynload/_sqlite3.cpython-35m-x86_64-linux-gnu.so
- If you see a line like
libsqlite3.so.0 => /usr/lib/x86_64-linux-gnu/libsqlite3.so.0 (0x00007f...), that means the module is dynamically linking the system's SQLite shared library. - If there's no mention of
libsqlite3.soin the output, the module was built with SQLite statically linked.
Method 2: Compare SQLite versions (Python vs. system)
You can cross-check the SQLite version used by Python against the system's installed version:
In a Python shell, run:
import sqlite3 print("Python's SQLite version:", sqlite3.sqlite_version)Check the system's SQLite version in the terminal:
sqlite3 --version # Or dpkg -l libsqlite3-0 to get the package version
- If the versions match, it's almost certainly using the system's shared library.
- If they differ, the Python module was likely built with a statically linked SQLite copy (common in custom Python builds).
Method 3: Inspect dynamic symbols with objdump
Another way to confirm dynamic dependencies is using objdump to check the "NEEDED" flags of the shared object:
objdump -x /usr/lib/python3.5/lib-dynload/_sqlite3.cpython-35m-x86_64-linux-gnu.so | grep NEEDED
- A line reading
NEEDED libsqlite3.so.0confirms dynamic linking. - No such line means static linking.
Quick recap of the import chain
As you noted, when you import sqlite3 in Python 3.5, the call flow is:
import sqlite3→sqlite3/__init__.py: from sqlite3.dbapi2 import *→sqlite3/dbapi2.py: from _sqlite3 import *→ loads the shared object/usr/lib/python3.5/lib-dynload/_sqlite3.cpython-35m-x86_64-linux-gnu.so
This shared object is the actual bridge between Python and SQLite—so checking its dependencies tells you everything you need to know.
内容的提问来源于stack exchange,提问作者Basj

