跳到正文
DEV Community· Wenlo·· 3 天前AI 評分54

如何不先使用 pip,診斷 Python 套件匯入問題

Diagnose an import without reaching for pip first

AI 導讀

Wenlo 示範一套離線 Python 依賴診斷方法,分別檢查模組發現、套件中繼資料、匯入結果和小型操作。示例不會安裝套件或發出網絡請求;該次執行中 Python 為 3.14.10,NumPy 為 2.4.6,pandas 為 3.0.3,JSON 和 NumPy 小型操作通過,pandas 匯入成功,缺失模組未找到。

正文

Wenlo

Wenlo

Posted on Nov 19 AI-assisted

“The package does not work” can mean several different things: Python cannot discover it, distribution metadata is missing, importing it fails, or one particular operation is unsupported. This offline diagnostic separates those stages instead of treating an installation command as the first answer.

Run the example

All illustrative records are fictional. Save the following as dependency_diagnostics.py. The complete script was run in PythonIDE on iPhone; the screenshots show its actual source and output.

import importlib
import importlib.util
from importlib import metadata
from pathlib import Path
import sys

# Import names and distribution names are separate concepts.
checks = [('json', None), ('numpy', 'numpy'),
          ('pandas', 'pandas'),
          ('_lesson_missing_module_', None)]

def inspect_package(module_name, distribution):
    print(f'\nMODULE: {module_name}')
    spec = importlib.util.find_spec(module_name)
    if spec is None:
        print('Discovery: not found on the current search path')
        return
    origin = spec.origin or '<namespace>'
    display = Path(origin).name if origin not in {'built-in', 'frozen'} else origin
    print('Discovery: found; origin filename:', display)
    if distribution:
        try:
            print('Distribution version:', metadata.version(distribution))
        except metadata.PackageNotFoundError:
            print('Distribution metadata: absent (import may still work)')
    try:
        module = importlib.import_module(module_name)
    except Exception as error:
        print('Import failed:', type(error).__name__)
        print('A found module can still have a broken dependency.')
        return
    print('Import: succeeded')
    if module_name == 'json':
        payload = {'samples': [2, 4, 6]}
        assert module.loads(module.dumps(payload)) == payload
        print('JSON round-trip: passed')
    if module_name == 'numpy':
        array = module.array([2, 4, 6])
        assert int(array.sum()) == 12
        print('Small array operation: passed')

print('OFFLINE DEPENDENCY CHECK')
print('Python:', sys.version.split()[0])
for module_name, distribution in checks:
    inspect_package(module_name, distribution)
print('\nNo installation or network request was performed.')
print('Compare discovery, metadata, import, and actual use separately.')

Dependency diagnostic source, part 1

Dependency diagnostic source, part 2

Actual dependency diagnostic output in PythonIDE

Understand the checks and their limits

find_spec checks discovery on the current import path. Metadata lookup asks about a distribution, whose name need not match the import name. import_module actually imports it, and the tiny JSON/NumPy checks exercise a behavior. A successful import is weaker evidence than a passing operation, and a passing tiny operation is not proof that every API works.

The deliberately missing module should be reported as not found; other results depend on the runtime. Missing distribution metadata does not prove that a bundled module is unavailable. A nearby file named numpy.py can shadow the intended package, so compare origin information during diagnosis. The report prints only an origin filename to avoid needlessly exposing a full local path. No installation, upgrade, or network request occurs.

Try one change

Add matplotlib and a small nonvisual operation before attempting a chart. If discovery succeeds but import fails, record the exception class and investigate the full traceback locally instead of assuming a reinstall will fix it.

I build PythonIDE, a Python coding app for iPhone and iPad. The example is intended to teach a workflow you can inspect and adapt.

AI assisted with drafting and translation. The example was run and its output checked in PythonIDE.

Observed run

In this run, Python reported 3.14.10, NumPy 2.4.6 and pandas 3.0.3. JSON and the small array check passed; pandas imported successfully; the deliberately missing module was not found. These version numbers describe this runtime, not every installation.

View PythonIDE on the App Store

來源:DEV Community · dev.to