Conda python环境管理

conda存在形态

交互入口环境配置环境文件罗列环境创建环境切换环境删除环境
Anaconda Prompt 命令行终端(CLI)~\.condarc
(定义加密,envs目录,包目录,源定义)
..\envsconda env listconda create -n py314 python=3.14conda activate py314conda env remove -y -n py314
Anaconda Navigator 客户端(GUI)env列表点击创建env点环境点remove
pycharm 设置(IDE)interpreter>local conda点创建conda点exist condashow all>移除,逻辑删
  • 隐藏终端的激活环境信息长路径:conda config --set env_prompt ‘({name})’
  • 残留wheel.exe.c~.conda_trash.conda_trash:

conda部署

  • 安装miniconda后就可以用conda命令了
  • 检查环境:conda doctor
  • 变动记录:conda list --revisions
  • 修复元数据:conda repair
  • 版本回滚:conda install --revision REV_NUM 回滚重置当前环境,默认为0
  • 清理卸载
    • 卸载 miniconda3
    • 删除用户配置文件和缓存:rd /s /q "%USERPROFILE%\.conda" "%USERPROFILE%\.condarc" "%USERPROFILE%\.continuum"
    • 删除pip残留:rd /s /q "%APPDATA%\Python"
    • 清理终端启动逻辑:reg delete "HKCU\Software\Microsoft\Command Processor" /v "AutoRun" /f
    • 清理环境变量:搜conda
    • 验证:where conda

conda源管理

  • conda info 查看当前所有的源信息
  • conda config --show-sources(罗列本地源和仓库源)
  • conda config --show channels(罗列仓库源)
  • conda config --remove channels 源名称或链接 (移除仓库源)
  • conda config --add channels 源名或链接 (添加仓库源)
ssl_verify: true
show_channel_urls: true

## custom local dir
envs_dirs:
  - D:\codePython\python\anaconda3
pkgs_dirs:
  - D:\codePython\anaconda3\pkgs

#proxy_servers:
#  http: http://127.0.0.1:1081

channels:
  - defaults

# channel - qinghua
default_channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
  conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch-lts: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  deepmodeling: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/

conda自身升级

  • Anaconda Prompt
    • conda activate base
    • conda clean --tarballs
    • conda update conda
    • conda update --all
    • conda init --reverse
  • pycharm报错lateinit propety envs_dir has not been initialized
    • conda降级 conda install conda=25.9.1
    • conda info --envs
    • pycharm 按 Shift+Shift,搜索 "Invalidate Caches" > Invalidate and Restart
    • conda init --reverse > pycharm重启 > conda init

python环境管理

  • 可用python版本:conda search python
  • 环境目录:conda config --show envs_dirs
  • 环境列表
    • conda env list
    • conda info --envs
  • 终端初始化:conda init  切换不过去时需要执行一下
  • 切换环境:conda activate tx314
  • 当前环境:Get-Command python | Select-Object Source
  • 创建环境:
    • 指定源:conda create -n py314 python=3.14 -c https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
    • 指定源 + 安装包:conda create -n py314 python=3.14 numpy pandas -c https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
    • 32位:conda create -n py314 python=3.14 -override-channels --subdir win-32 -c https://repo.anaconda.com/pkgs/main
    • 临时代理:set ALL_PROXY=socks5://127.0.0.1:7890 只在当前终端临时生效
    • 克隆:conda create -n new_env --clone old_env
  • 删除环境
    • 移出列表:conda remove -n test
    • 物理删除:conda remove -n test --all
    • 清理conda安装包缓存:conda clean -t
    • 清理环境未使用的包缓存:conda clean -p -n test
  • pip安装包
    • 查看包来源
      • python -m site
      • conda info
    • 查看pip配置:pip config list
      • 安装时,用了 --user, 会安装到用户级python包环境下,并被conda创建的环境共享
      • 解决:激活环境下,把这些包都卸载了。再次安装即可
    • pip指定源安装pip install -i https://pypi.tuna.tsinghua.edu.cn/simple torch torchvision (优先使用这个,结尾会打印一共装了哪些包,方便做笔记)
    • pip指定源安装:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn  torch torchvision
    • conda搜索包:conda search torch -c https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
    • conda安装:conda install -c conda-forge ffn
    • conda安装加速:conda install -c conda-forge ffn --solver=libmamba
    • conda指定源安装:conda install -n myenv torch torchvision -c pytorch -c https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
    • conda安装cpu版本:conda install torch torchvision -c pytorch
    • conda安装gpu版本:conda install -n myenv torch torchvision pytorch-cuda=12.1 -c pytorch -c nvidia
  • 环境重置脚本

    #!/usr/bin/env python3
    # coding=utf-8
    """
    @File : utils_reset_python_env.py
    @Author  : AT
    @Create  : 2023/6/16 15:52
    @Desc    : 切换到需要重置清空的python环境,运行main方法或本文件即可
    """
    import sys
    import platform
    import pkg_resources
    import subprocess
    
    def reset_packages_init(_init_list=['pip', 'setuptools', 'wheel']):
        _print_python_interpreter()
        _exist_list = _get_packages()
        print(f"当前环境:初始化为: ({' '.join(_init_list)})")
        _remove_list = list(set(_exist_list) - set(_init_list))
        if _remove_list:
            print(f"当前环境:pip uninstall -y {' '.join(_remove_list)}")
        user_input = input("当前环境:pip uninstall continue: 0-No(默认), 1-Yes")
        print(f'当前环境:pip uninstall continue:: 你的选择 = {user_input}')
        if user_input == '1':
            for _package in _remove_list:
                _uninstall_package(_package)
            _get_packages()
        sys.exit()
    
    
    def _print_python_interpreter():
        print(f"当前环境:python版本={platform.python_version()}, 解释器路径={sys.executable})")
    
    def _get_packages():
        # 获取当前 Python 系统中所有已安装包的列表
        installed_packages = pkg_resources.WorkingSet()
        installed_packages_name = [dist.project_name for dist in installed_packages]
        print(f"当前环境:installed_packages=({' '.join(installed_packages_name)})")
        return installed_packages_name
    
    def _uninstall_package(package):
        try:
            subprocess.run(['pip', 'uninstall', '-y', package])
        except Exception as e:
            print(f"卸载:{package} 失败!An error occurred: {e}")
    
    if __name__ == '__main__':
        reset_packages_init()

jupyter管理

  • jupyter部署
    • 安装jupyter内核管理包:pip install ipykernel
    • 安装jupyterlab界面:pip install --upgrade jupyter jupyterlab notebook ipykernel jupyter_client jupyter_core traitlets (python 3.14 内核,jupyter单元格import sys卡住时,可以安装这些)
    • 启动服务:jupyter notebook 
    • 卸载

      conda activate your_env_name
      
      conda uninstall --force-remove -y jupyter jupyterlab notebook jupyter_server jupyter_core jupyter_client nbconvert nbformat nbclient ipykernel ipywidgets widgetsnbextension jupyter_console qtconsole jupyterlab_widgets jupyterhub notebook-shim traitlets send2trash terminado argon2-cffi prometheus_client pyzmq tornado nest-asyncio comm jupyter-events jupyter-lsp jupyter_server_terminals jupyterlab_pygments jupyterlab_server jupyter_server_fileid jupyter_server_ydoc jupyter_ydoc jupyterlab-debugger
      
      pip uninstall -y jupyter jupyterlab notebook jupyter_server jupyter_core jupyter_client nbconvert nbformat nbclient ipykernel ipywidgets widgetsnbextension jupyter_console qtconsole jupyterlab_widgets traitlets send2trash terminado argon2-cffi prometheus_client pyzmq tornado nest-asyncio comm jupyter-events jupyter-lsp jupyter_server_terminals jupyterlab_pygments jupyterlab_server jupyter_server_fileid jupyter_server_ydoc jupyter_ydoc jupyterlab-debugger
      
      私有kernel会在卸载python环境时清除,卸载jupyter时不处理
      用户共享的kernel配置单独维护,不和jupyter耦合
  • kernel全局部署
    • 共享机制:Jupyter 的 kernel 配置默认是全局共享的,记录在用户级目录下,而不是每个 Python 环境各自独立存放。
    • 查看:jupyter kernelspec list
    • 创建共享kernelpython -m ipykernel install --user --name lstm314 --display-name "Python (lstm314)" (在什么环境执行,就分享哪个kernel)
    • 私有kernel:python -m ipykernel install --sys-prefix --name lstm314 --display-name "Python (lstm314)"
    • 删除:jupyter kernelspec uninstall lstm314

      jupyter和业务kernel隔离架构
      
      Jupyter专用环境(名为 jupyter_lab)
      ├── 只安装:jupyterlab + ipykernel(必须,其他可选)
      └── 负责启动 jupyter lab
      
      业务环境1(名为 lstm314)
      ├── 只安装业务包:pandas, numpy, torch, 你的项目等
      └── 不安装任何 jupyter* 包
      
      业务环境2(名为 quant3810)
      ├── 只安装另一套业务包
      └── 不安装任何 jupyter* 包
      
      # 先激活业务环境(确保用的是它的 python 和包路径)
      conda activate lstm314
      pip install ipykernel  # 最小的轻量包,只用来分享内核
      
      # 用 Jupyter 专用环境的 ipykernel 来注册
      python -m ipykernel install --user --name lstm314 --display-name "Python (lstm314)"
  • 启动jupyter
    • jupyter notebook 启动服务并打开老版界面(需要在有jupyter包的环境下执行)
      • --ip=0.0.0.0 --no-broswer 绑定服务ip
      • --port 8889 指定端口号
    • jupyter lab 启动服务并打开新版界面
    • tasklist | findstr python | findstr jupyter 查看 进程
    • jupyter lab stop 结束进程
       
  • 功能增强
    • 中文版
      pip install jupyterlab-language-pack-zh-CN
    • 语法提示功能
    • pip uninstall jupyterlab-lsp -y
      pip install jupyterlab-lsp --no-cache-dir
    • # 纯 Python 方式安装语言服务(无需编译)
      pip uninstall jupyterlab-lsp -y
      pip install jupyterlab-lsp --no-cache-dir
      # 补全 python-lsp-server[all] 可选依赖
      
      
      # 可选:轻量构建(关闭压缩,避免内存溢出)依赖node.js
      jupyter lab build --dev-build=False --minimize=False
      
      # 生成配置文件(如果已存在会提示覆盖,选 N)
      jupyter lab --generate-config
      # 用记事本打开配置文件
      notepad C:\Users\cat\.jupyter\jupyter_lab_config.py
      ----------------写入以下内容---------------
      c = get_config()
      ----------------写入以上内容---------------
      # 查看插件状态
      jupyter labextension list

      代码补全:需要按一下tab

    • debuger:内核旁边的虫子图标