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

PyCharm运行Python脚本提示tensorflow模块不存在排查求助

排查PyCharm中虚拟环境tensorflow包无法识别的问题

问题场景

通过PyCharm创建Python项目,代码包含tensorflow.keras相关导入:

import numpy as np
from tensorflow.keras import layers, models, optimizers, utils, datasets


def print_hi(name):
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

运行时出现错误:

Traceback (most recent call last):
  File "C:\Users\max\PycharmProjects\pythonProject\main.py", line 2, in <module>
    from tensorflow.keras import layers, models, optimizers, utils, datasets
ModuleNotFoundError: No module named 'tensorflow'

已在虚拟环境中安装tensorflow,但程序疑似使用全局环境,切换解释器无效,可按以下步骤排查:


排查步骤

  • 确认运行配置的解释器
    点击PyCharm右上角的运行配置下拉框,选择「Edit Configurations...」,在弹出窗口中检查「Python interpreter」选项,确认是否选中了项目对应的虚拟环境(路径通常为项目目录下venv\Scripts\python.exe(Windows)或venv/bin/python(Mac/Linux))。

  • 验证虚拟环境的tensorflow安装状态
    打开PyCharm内置Terminal,确认命令行开头有(venv)标识(虚拟环境已激活),执行pip list查看输出中是否包含tensorflow;如果未激活虚拟环境,Windows手动执行venv\Scripts\activate,Mac/Linux执行source venv/bin/activate后再检查。

  • 检查项目全局解释器设置
    打开「File > Settings > Project: [你的项目名] > Python Interpreter」(Windows/Linux)或「PyCharm > Settings > Project: [你的项目名] > Python Interpreter」(Mac),确认选中的是目标虚拟环境,且下方包列表中存在tensorflow;若不存在,点击右侧「+」按钮搜索tensorflow并安装到该环境。

  • 验证当前解释器路径
    在代码中添加以下测试代码并运行:

    import sys
    print(sys.executable)
    

    输出路径应为虚拟环境内的Python可执行文件路径,若为全局Python路径,说明运行配置未正确关联虚拟环境,需重新配置。

  • 清理缓存并重启PyCharm
    点击「File > Invalidate Caches...」,选择「Invalidate and Restart」,让PyCharm重新加载项目配置与包信息。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:35:16