Python 生態(tài)工具
工欲善其事,必先利其器,掌握主流實(shí)用工具,優(yōu)點(diǎn)很多,可以顯著提升編程效率,形成統(tǒng)一代碼風(fēng)格,通過(guò)工具自學(xué)Python,任意切換 / 管理不同工作環(huán)境等。
2.1 Python 內(nèi)置小工具
內(nèi)置下載服務(wù)器
python -m SimpleHTTPServer
python -m http.server # python3
執(zhí)行上述命令,會(huì)在當(dāng)前目錄下啟動(dòng)一個(gè)文件下載服務(wù)器,默認(rèn)打開8000端口。
字符串轉(zhuǎn)換為 json
工作中,系統(tǒng)會(huì)調(diào)用底層服務(wù)的 API。底層服務(wù)的 API 一般都是以 JSON 格式返回,為了便于問(wèn)題追蹤,會(huì)將 API 返回的 JSON 轉(zhuǎn)換為字符串記錄到日志文件中。當(dāng)需要分析問(wèn)題時(shí),需要將日志文件中的 JSON 字符串拿出來(lái)進(jìn)行解析。即需要將一個(gè) JSON 字符串轉(zhuǎn)換為 JSON 對(duì)象,以提高日志的可讀性。
[baiyongan@bya ~]$ echo '{"address": {"province": "jiangsu", "city": "nanjing"}, "name": "baiyongan", "role": "superman"}' | python -m json.tool
{
"address": {
"city": "nanjing",
"province": "jiangsu"
},
"role": "superman",
"name": "baiyongan"
}
# 前面是json 字符串,后面接管道與python -m json.tool
檢查第三方庫(kù)是否正確安裝
如果使用腳本對(duì)大批量的服務(wù)器進(jìn)行自動(dòng)部署,可以使用python解釋器的 -c 參數(shù)快速地執(zhí)行import 語(yǔ)句。
最關(guān)鍵——可以在腳本中實(shí)現(xiàn)對(duì)遠(yuǎn)程服務(wù)器地驗(yàn)證操作。
2.2 pip 高級(jí)用法
pip常用命令
| 子命令 | 功能 |
|---|---|
| install | 安裝 如:pip install flask==0.8 安裝特定版本 |
| download | 下載 |
| uninstall | 卸載 |
| freeze | 按照requirements 格式輸出安裝包,pip freeze > requirements.txt 可以到其他服務(wù)器上執(zhí)行 pip install -r requirements.txt 直接安裝軟件 |
| list | 列出當(dāng)前系統(tǒng)中的安裝包 |
| show | 查看安裝包的信息:版本、依賴、許可證、作者、主頁(yè)等 |
| check | 檢查安裝包的依賴是否完整 |
| search | 查找 |
| wheel | 打包軟件到wheel格式 |
| hash | 計(jì)算安裝包的hash值 |
| completion | pip completion --bash >> ~/.profile $ source ~/.profile 通過(guò)鍵入'pip i<tab>',將會(huì)自動(dòng)輸入 'pip install' |
| help | 獲取pip 和子命令的幫助信息 |
如何加速pip的安裝
方法一:更改鏡像源
豆瓣:http://pypi.douban.com/simple/
清華:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
臨時(shí)使用,如下:只有安裝pillow時(shí)使用指定源
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple pillow
永久修改,修改配置文件
Linux下,修改 ~/.pip/pip.conf (沒有就創(chuàng)建一個(gè)), 修改 index-url至tuna,內(nèi)容如下:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simplewindows下,直接在user目錄中創(chuàng)建一個(gè)pip目錄,如:C:\Users\xx\pip,新建文件pip.ini,內(nèi)容如下:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple-
PyCharm 中更改鏡像源
File >> Settings >> Project >> Project Interpreter >> (右側(cè)邊緣 + 號(hào)) Available Packages >> Manage Repositories >> 右側(cè)邊緣加號(hào) >> input a repository URL >> 清華、豆瓣等
方法二:將軟件下載到本地部署
如果服務(wù)器無(wú)法連接外網(wǎng),且安裝包較多較大,可以先將包下載到本地,然后從本地安裝。
# 下載到本地
pip install --download='pwd' -r requirements.txt
# 本地安裝
pip install --no-index -f file://'pwd' -r requirements.txt
2.3 Python編輯器
Linux 用 vim:代碼補(bǔ)全插件 snipmate、語(yǔ)法檢查插件 Syntastic、編程提示插件 jedi-vim
windows 用Pycharm
2.4 Python 編程輔助工具
Python 交互式編程:IPython Shell 和 jupyter (IPython Notebook)
IPython: 略
jupyter:略
2.5 Python 調(diào)試器
單步調(diào)試 標(biāo)準(zhǔn)庫(kù) 的pdb 以及第三方庫(kù)ipdb
ipdb 之于pdb,就相當(dāng)于 IPython 之于Python
標(biāo)準(zhǔn)庫(kù)的pdb:部分調(diào)試命令
一種是直接在命令行參數(shù)指定使用pdb模塊啟動(dòng)python 文件,適用于文件較短的程序
python -m pdb test_pdb.py
另一種,直接在代碼中,調(diào)用set_trace方法設(shè)置斷點(diǎn),適用于程序文件較大的場(chǎng)景
from __future__ import print_function
import pdb
import ipdb
def sum_nums(n):
s = 0
for i in range(n):
pdb.set_trace()
# ipdb.set_trace()
s += i
print(s)
if __name__ == '__main__':
sum_nums(5)
2.6 Python 代碼規(guī)范檢查
PEP8 編碼規(guī)范 : 對(duì)齊規(guī)則、包導(dǎo)入順序、空格與注釋、命名習(xí)慣、異常處理等
google Python 編碼風(fēng)格
- pycodestyle 檢查代碼規(guī)范
[root@bya Test_Project]# cat test.py
import os,sys
def main():
print([ITEM FOR ITEM IN OS.LISTDIR('.') if item.endswith('.py')]);
print( sys.version)
if __name__ == __main__:
main()
[root@bya Test_Project]# pycodestyle --show-source test.py # 使用 --show-source 顯示出錯(cuò)源碼
test.py:1:10: E231 missing whitespace after ','
import os,sys
^
test.py:1:10: E401 multiple imports on one line
import os,sys
^
test.py:3:1: E302 expected 2 blank lines, found 1
def main():
^
test.py:4:70: E703 statement ends with a semicolon
print([ITEM FOR ITEM IN OS.LISTDIR('.') if item.endswith('.py')]);
^
test.py:5:11: E201 whitespace after '('
print( sys.version)
^
test.py:7:1: E305 expected 2 blank lines after class or function definition, found 1
if __name__ == __main__:
^
[root@bya Test_Project]#
- 使用autopep8 將代碼格式化
autopep8 --in-place test.py # 相當(dāng)于sed 里面的-i 選項(xiàng),直接將修改結(jié)果保存到源文件中
# autopep8 還有--aggressive 選項(xiàng),使用該選項(xiàng), 會(huì)執(zhí)行更多實(shí)質(zhì)性的更改,多次使用,效果更佳。
- pylint 代碼審查工具
2.7 Python 工作環(huán)境管理
pyenv 用于管理不同的Python 版本:如工作時(shí)用Python 2.7.13, 學(xué)習(xí)時(shí)用Python 3.6.0
virtualenv 用于隔離不同項(xiàng)目的工作環(huán)境:如都在Python 2.7.13 中,項(xiàng)目A用flask 0.8,項(xiàng)目B用flask 0.9
組合使用pyenv 和virtualenv,就能夠構(gòu)造Python 和第三方庫(kù)的任意版本組合。
virtualenv是一個(gè)獨(dú)立工具,用戶可以不用pyenv, 而單獨(dú)用virtualenv,但如果用了pyenv,則需要安裝pyenv-virtualenv插件。
- 安裝 pyenv
[root@bya Test_Project]# git clone https://github.com/yyuu/pyenv.git ~/.pyenv
Cloning into '/root/.pyenv'...
remote: Enumerating objects: 29, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 17972 (delta 9), reused 10 (delta 3), pack-reused 17943
Receiving objects: 100% (17972/17972), 3.55 MiB | 14.00 KiB/s, done.
Resolving deltas: 100% (12236/12236), done.
[root@bya Test_Project]# echo 'export PYENV_ROOT="$HOME"/.pyenv' >> ~/.bash_profile
[root@bya Test_Project]# echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
[root@bya Test_Project]# echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
[root@bya Test_Project]# source ~/.bash_profile
[root@bya Test_Project]# pyenv --help
Usage: pyenv <command> [<args>]
Some useful pyenv commands are:
commands List all available pyenv commands
exec Run an executable with the selected Python version
global Set or show the global Python version(s)
help Display help for a command
hooks List hook scripts for a given pyenv command
init Configure the shell environment for pyenv
install Install a Python version using python-build
local Set or show the local application-specific Python version(s)
prefix Display prefix for a Python version
rehash Rehash pyenv shims (run this after installing executables)
root Display the root directory where versions and shims are kept
shell Set or show the shell-specific Python version
shims List existing pyenv shims
uninstall Uninstall a specific Python version
version Show the current Python version(s) and its origin
--version Display the version of pyenv
version-file Detect the file that sets the current pyenv version
version-name Show the current Python version
version-origin Explain how the current Python version is set
versions List all Python versions available to pyenv
whence List all Python versions that contain the given executable
which Display the full path to an executable
See `pyenv help <command>' for information on a specific command.
For full documentation, see: https://github.com/pyenv/pyenv#readme
[root@bya Test_Project]#
- pyenv 的使用
pyenv install --list # 查看支持版本
pyenv install -v 3.6.0 # 安裝某個(gè)Python 版本
pyenv versions # 查看當(dāng)前系統(tǒng)中的Python版本
pyenv global 2.7.5 # 切換至 2.7.5 版本
pyenv uninstall 2.7.5 # 刪除2.7.5 版本
- 安裝pyenv-virtualenv插件
[root@bya Test_Project]# git clone https://github.com/yyuu/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv
Cloning into '/root/.pyenv/plugins/pyenv-virtualenv'...
remote: Enumerating objects: 2064, done.
remote: Total 2064 (delta 0), reused 0 (delta 0), pack-reused 2064
Receiving objects: 100% (2064/2064), 580.31 KiB | 14.00 KiB/s, done.
Resolving deltas: 100% (1413/1413), done.
[root@bya Test_Project]# echo 'eval "$(pyenv virtualenv-init -)"' >>~/.bash_profile
[root@bya Test_Project]# source ~/.bash_profile
[root@bya Test_Project]# pyenv help virtualenv
Usage: pyenv virtualenv [-f|--force] [VIRTUALENV_OPTIONS] [version] <virtualenv-name>
pyenv virtualenv --version
pyenv virtualenv --help
-f/--force Install even if the version appears to be installed already
[root@bya Test_Project]#
- 使用pyenv-virtualenv插件
pyenv virtualenv 2.8.5 first_project # 新建兩個(gè)工作環(huán)境
pyenv virtualenv 2.8.5 second_project
pyenv virtualenvs # 查看工作環(huán)境
pyenv activate first_project # 進(jìn)入一個(gè)工作環(huán)境
(first_project) $ pip install flask==0.8
(first_project) $ pyenv deactivate # 退出一個(gè)工作環(huán)境
pyenv virtualenv-delete first_project # 刪除一個(gè)虛擬環(huán)境
總結(jié)
IPython這一塊沒有寫,setuptools 工具也沒寫。
重點(diǎn)是要知道工具的存在,并且知道哪些工具解決哪些問(wèn)題。