Python手册(1) Anaconda & pip

0. 资料

1. Anaconda

1.1. 安装

  • 建议使用清华镜像下载,安装完成后执行。

    1
    2
    3
    conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
    conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
    conda config --set show_channel_urls yes
  • Windows直接安装。

  • Ubuntu安装如下

    1
    2
    sudo bash Anaconda3-4.3.0-Linux-x86_64.sh 
    # 一路回车+yes(注意最后一步是问是否要将Anaconda安装到系统路径)
  • centos安装:

    • 需要先安装bunzip2,命令为 yum install -y bzip2,否则会报错 bunzip2: command not found
    • 之后就 bash Anaconda3-4.3.0-Linux-x86_64.sh 即可。

1.2. 环境相关

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 安装
conda create --name tensorflow python=3.6

# 激活
activate tensorflow # Windows
source activate tensorflow # Linux & Mac

# 撤销激活
deactivate tensorflow # Windows
conda deactivate tensorflow # Linux & Mac

# 删除
conda remove --name tensorflow --all

# 复制某环境
conda create --name new_env --clone old_env

# 重命名环境:先复制再删除

1.3. package相关

1
2
3
4
conda list
conda install numpy
conda uninstall numpy
conda install tensorflow-gpu=1.12.0

1.4. 修改envs和pkgs的默认路径

  • 默认envs和pkgs位于~/anaconda3目录下,占用空间太多。

  • 可以修改 ~/.condarc 来设置envs和pkgs的路径。经过下面的配置,新环境将安装在/path/to/new/envs中,但如果环境在 /path/to/new/envs 中不存在,就会到 /home/ubuntu/anaconda3/envs 中寻找有没有对应的环境。

    1
    2
    3
    4
    5
    6
    envs_dirs:
    - /path/to/new/envs
    - /home/ubuntu/anaconda3/envs
    pkgs_dirs:
    - /path/to/new/pkgs
    - /home/ubuntu/anaconda3/pkgs
  • 经过上面修改后,旧环境可能会报错,类似于:

    • -bash: /usr/local/bin/pip: /usr/bin/python: bad interpreter: No such file or directory
    • 解决方法是进入虚拟环境后,执行命令 python -m pip install --upgrade pip.

1.5. 设置启动/结束脚本

  • 功能描述:在运行 conda activate envconda deactivate 时可以运行响应的脚本。
  • 应用举例:可以在脚本中设置环境变量。
  • 设置方法:
    • 对于每个环境,假设其根目录为 /path/to/env/
    • 运行 conda activate env 时启动的脚本可以在 /path/to/env/etc/conda/activate.d/ 中建立。
    • 运行 conda deactivate 时启动的脚本可以在 /path/to/env/etc/conda/deactivate.d/ 中建立。
    • 如果上述两个目录不存在,可以自己手动建立。

1.6. 碰到的问题

  • 使用Conda安装Keras时,不能使用tensorflow-gpu版,只能使用cpu版。
    • 解决方案:要么 keras 和 tensorflow 分别安装,要么使用 keras-gpu。
  • 不能安装happybase。
    • 解决方案:使用pip安装。

2. pip

2.1. 镜像

2.2. 其他

  • 指定版本:pip install tensorflow==1.12.0