python环境准备
创建一个新的python项目,一般情况下要使用python的虚拟环境,下面介绍两种方式:
# 1. 首先需要电脑上有python解释器(如果没有请先安装)
# 2. 安装 virtualenv
pip install virtualenv
pip install virtualenvwrapper-win # 包管理
# 可以将python解释器和virtual都加到系统的环境变量中,方便直接在终端中使用
# 如果是windows需要在系统环境变量中新建一个变量存放虚拟环境的目录
# WORKON_HOME 存放路径
# 3. 创建虚拟环境
# 如果电脑中只安装了一个Python解释器,可以不指定解释器,多个的时候要指定 -p
mkvirtualenv 虚拟环境名称 [-p python的路径(如 /usr/bin/pythonX)]
# 4. 进入虚拟环境:
workon 虚拟环境名称
# 5. 退出虚拟环境:
deactivate
# 6. 删除虚拟环境:
rmvirtualenv 虚拟环境名称
# 0. linus系统查找自带python解析器版本,一般在/usr/bin目录下
find /usr/bin -name 'python*'
# 查看默认解释器的版本
python -V
# 1. centos下安装anaconda
# 1.1 anaconda3-2023.05-linus-x86_64.sh上传到centos中,并执行下个命令安装,安装过程中可以指定安装目录,不指定则在用户的家目录下
sh ./anaconda3-2023.05-linus-x86_64.sh
# 1.2 安装成功,终端会出现 (base)前缀,如(base) [myhadoop@hadoop100 ~],如果没有出现,需要
source bin/activate
# 1.3 更新国内源,~/.condarc文件中追加
channels:
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
- defaults
show_channel_urls: true
# 或者使用命令添加
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/
# 设置搜索时显示通道地址
conda config --set show_channel_urls yes
# 2. windows安装
# 如果没有加入到环境变量,则需要切到C:\ProgramData\Anaconda3打开终端,激活环境
activate.bat
# 也可以直接 打开 Anaconda Prompt (anaconda3)、
# 3. 查看conda env 列表
conda env list
# 4. 创建虚拟环境(需要先激活base环境才行 source bin/activate),可以指定安装python的版本
conda create -n datax python=3.8
# 5. 使用虚拟环境,默认在anaconda下的envs中
conda activate datax
# 6. 退出虚拟环境
conda deactivate
比较出名的源有:
如果是windows可以在python目录的pip文件夹下,新增pip.ini,添加如下内容:
[global]
timeout = 6000
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = https://pypi.tuna.tsinghua.edu.cn
# 1. 安装
pip install django==4.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
# 2. 卸载
pip uninstall django
# 3. 包列表
pip list
# 4. 直接安装文件(以docx模块为例)
# 下载 python_docx-0.8.7-py2.py3-none-any.whl 链接
pip install python_docx-0.8.7-py2.py3-none-any.whl
# 1. 导出环境
# 进入到 迁出项目 目录下的命令行,运行命令导出环境依赖
pip freeze > requirements.txt
# 或者(如果导出的环境有些奇怪的内容)
pip list --format=freeze > requirements.txt
# 2. 导入环境
# 将 requirements.txt 放入到 迁入项目 的目录下,在命令行输入
pip install -r requirements.txt [-i https://pypi.tuna.tsinghua.edu.cn/simple]