Python使用笔记
开发环境配置
1、pip更改默认源
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple
2、使用默认源
pip config set global.index-url https://pypi.org/simple
3、临时更改源
pip install scrapy -i https://pypi.tuna.tsinghua.edu.cn/simple
4、Anaconda 换国内源
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/
或者修改user目录下.condarc文件内容为
channels:
- http://mirrors.aliyun.com/anaconda/pkgs/main
- http://mirrors.aliyun.com/anaconda/pkgs/r
- http://mirrors.aliyun.com/anaconda/pkgs/msys2
show_channel_urls: true
5、设置搜索时显示通道地址
conda config --set show_channel_urls yes
6、安装虚拟环境
pip install virtualenv virtualenvwrapper
7、进入虚拟环境
workon dl4cv
8、退出虚拟环境
deactivate
9、conda创建虚拟环境,删除虚拟环境
conda create -n your_env_name python=x.x
conda remove -n your_env_name --all
conda env remove -p your_env_path
10、检查更新conda
conda update conda
Python内建函数
1、enumerate遍历序列的同时获取当前元素索引
for i, value in enumerate:
# 使用i值做点事情
2、字典合并
d1 = {'key1': vaule1, 'key2': value2}
d2 = {'key3': value3, 'key4': value4}
d1.update(d2)
# 输出d1为{'key1': vaule1, 'key2': value2, 'key3': value3, 'key4': value4}
3、字典删除pop、字典获取get
# pop、get方法均可以返回一个默认值,代替if-else写法
vaule = dic.get(key, default_value)
一些技巧
1、生成requirement依赖
pip freeze > requirements.txt
2、安装requirements.txt依赖
pip install -r requirements.txt
3、查看包信息,包括安装目录
pip show tensorflow
4、查看tensorflow所有可能的包版本(无效)
pip install yolk3k
yolk -V tensorflow
matplotlib画图中文显示失败
1、下载字体 https://wws.lanzous.com/iZUBSga57xg
2、找到python的包matplotlib
3、将字体拷贝到 matplotlib/mpl-data/fonts下
4、清空matplotlib字体缓存 rm -rf ~/.cache/matplotlib
5、mk matplotlib
6、fc-cache
7、编辑 matplotlib/matplotlibrc文件
font.familiy sans-serif
font.sans-serif: SimHei,FangSong
axes.unicode_minus: False
8、保存,重启项目
9、打包exe
pyinstaller -F -w -d
10、安装miniforge后无法直接使用pip
执行source ~/.bash_profile
后再使用pip
11、cannot import name ‘config’ from ‘tensorflow’ (unknown location)
安装错误,执行pip install --upgrade --ignore-installed tensorflow
覆盖重新安装
12、使用git忽略.ipynb的输出,执行pip install nbstripout
,然后在项目目录下执行nbstripout FILE.ipynb [FILE2.ipynb ...]
13、安装geopandas和basemap
安装顺序conda安装gdal、fiona、pyproj、shapely,然后pip安装basemap
14、vscode提示:不再支持与所选 kernel 关联的 Python 版本。请考虑选择其他 kernel。
通过conda upgrade conda
,conda update jupyter
升级kernel。
15、python中使用cplex,在C:\Program Files\IBM\ILOG\CPLEX_Studio221\cplex\python\3.x
目录中,以管理员权限执行python setup.py install
命令,将生成的build\lib
中的cplex目录拷贝至conda虚拟环境中的\Lib
目录下。
16、pysam安装
conda config --add channels defaults
conda config --add channels conda-forge
conda config --add channels bioconda
conda install pysam