You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

虚拟环境中Jupyter无法导入pytesseract的问题问询

问题分析与解决

问题重现

在Anaconda提示符的虚拟环境中安装pytesseract,执行以下命令:

conda create -y -n tesseract python=3.8
conda activate tesseract
conda install -c conda-forge pytesseract
conda install -c conda-forge tesseract
python -m ipykernel install --user --name=tesseract 

启动Jupyter Lab后运行代码:

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r'C:\Users\abc\Anaconda3\envs\tesseract\Library\bin\tesseract.exe'

出现错误:

Traceback (most recent call last):
    import pytesseract
ImportError: No module named pytesseract

将pytesseract包复制到C:\Users\abc\anaconda3\Lib\site-packages后错误消失。

核心原因

问题本质是Jupyter运行的Python解释器并非tesseract虚拟环境,而是Anaconda的base环境,具体原因主要有两点:

  1. 虚拟环境未安装ipykernel:
    执行python -m ipykernel install前,未在tesseract虚拟环境中安装ipykernel包。此时系统会调用base环境的ipykernel生成kernel配置,最终kernel指向base环境的Python解释器。Jupyter加载该kernel时,实际运行base环境的Python,自然找不到虚拟环境site-packages中的pytesseract。

  2. Jupyter Lab从base环境启动:
    即使kernel配置正确,若从base环境启动Jupyter Lab,可能出现路径识别异常,导致实际使用base环境的Python。

解决方案

方案1:重新配置正确的kernel

  1. 激活tesseract虚拟环境:
conda activate tesseract
  1. 在虚拟环境中安装ipykernel:
conda install ipykernel
  1. 重新安装kernel(覆盖原有配置):
python -m ipykernel install --user --name=tesseract --overwrite
  1. 重启Jupyter Lab,选择tesseractkernel运行代码。

方案2:从虚拟环境启动Jupyter Lab

  1. 激活tesseract虚拟环境:
conda activate tesseract
  1. 在虚拟环境中安装Jupyter Lab:
conda install jupyterlab
  1. 直接从虚拟环境启动Jupyter Lab:
jupyter lab

这种方式下,Jupyter默认使用当前虚拟环境的Python,无需额外配置kernel即可调用虚拟环境中的包。

验证方法

在Jupyter中运行以下代码,查看当前Python解释器路径,确认是否指向虚拟环境:

import sys
print(sys.executable)

若输出为C:\Users\abc\Anaconda3\envs\tesseract\python.exe,说明配置正确;若为base环境路径,需重新检查kernel配置。

内容的提问来源于stack exchange,提问作者RisingSun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 14:57:16