Python 必備好庫 - 好工具收藏

apscheduler

collections

  • collections.OrderDict
  • collections.defaultdict

Python 標準庫提供了 collections 模塊。這個方便的附加組件能夠爲你提供更多數據類型。html

from collections import OrderedDict, Counter
# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)
# Counts the frequency of each character
y = Counter("Hello World!")

ConfigParser

[PERCENT]
#配置文件對應的系統文件夾名
system_dir                     =C:\Users\michaelxiang\Desktop\get_report0906\get_report\maps
#請輸入佔總交易的百分比值(小數)
percent                         = 0.8
#決定是否只是篩選佔交易比重大的交易(y or n)
decision                     =y

[SUCC_VALUE]
#請輸入成功率閾值(1之內的小數)
default_succ_value   = 0.8
繳費                        =0.8
消費                        =0.8
行業帳單                   =0.8
行業信息查詢             =0.8

[KEEP_TIME]
default_keep_time    =60
繳費_持續時間        =60
消費_持續時間        =60
行業帳單_持續時間    =60
行業信息查詢_持續時間  =60
cf = configparser.ConfigParser()
# 讀取配置文件變量config,並指定編碼格式
cf.read(config, encoding='gb2312')
system_dir = cf.get('PERCENT', 'system_dir')
percent = float(cf.get('PERCENT', 'percent'))
decision = cf.get('PERCENT', 'decision')

# cf.options得到元祖對的列表[(,),(,)……]
succ_value_list = cf.options('SUCC_VALUE')
keep_time_dic = {x[0]: float(x[1]) for x in cf.items('KEEP_TIME')}

future

__ future__模塊容許用戶導入新版 Python 的功能。這簡直就像時間旅行,或者魔法什麼的:java

from __future__ import print_function
print("Hello World!")

functools

fake-useragent

假裝瀏覽器身份:python

pip install fake-useragent
from fake_useragent import UserAgent
ua = UserAgent()

ua.ie
ua.msie
ua.opera
ua.chrome

getsub

下載視頻字幕:linux

pip install getsub
getsub <視頻路徑>

gy

生成 .gitignore 文件:nginx

#https://www.gitignore.io/
$ pip install gy
$ gy generate python java lisp

id-validator

中華人民共和國居民身份證、中華人民共和國港澳居民居住證以及中華人民共和國臺灣居民居住證號碼驗證工具(Python 版):git

itertools

MyQR

生成 Python 藝術二維碼github

pip install MyQR
myqr https://github.com
myqr https://github.com -v 10 -l Q

ngxtop

解析 nginx 訪問日誌並格式化輸出算法

pip install ngxtop
$ ngxtop

operator

os

os.walk

for root, dirs, files in os.walk(system_dir):
    i += 1
    print(i)
    print(root)
    print('dirs')
    print(dirs)
    print('files')
    print(files)
1
C:\Users\michaelxiang\Desktop\get_report0906\get_report
['maps']
['a.py', 'b.py', 'get_report.py', 'judge_succ.py', 'maps.cfg']
2
C:\Users\michaelxiang\Desktop\get_report0906\get_report\maps
['2016-09-06-16-18-40']
['case.csv', 'data.csv', 'judge_succ.py', 'percent-2016-09-06-16-18-40.csv', 'report-2016-09-06-16-18-40.csv']
3
C:\Users\michaelxiang\Desktop\get_report0906\get_report\maps\2016-09-06-16-18-40
['PIT多渠道脫機並行測試']
['case.csv', 'data.csv']
4
C:\Users\michaelxiang\Desktop\get_report0906\get_report\maps\2016-09-06-16-18-40\PIT多渠道脫機並行測試
[]
['消費(傳統)-TPS消費(傳統)-成功率時間段2016-08-10 13-03-25-2016-08-10 13-06-25.png', '行業信息查詢-TPS行業信息查詢-成功率
時間段2016-08-10 13-03-25-2016-08-10 13-06-25.png', '行業帳單查詢-TPS行業帳單查詢-成功率時間段2016-08-10 13-03-25-2016-08-10 1
3-06-25.png']

能夠看到:sql

  • root:執行os.walk時的每次的目錄,會改變,由於會遍歷目錄下的每一層文件夾;
  • dirs: 目錄下有幾個文件夾,以列表存儲文件夾名;
  • files: 目錄下的文件,以列表存儲文件名;

os.listdir

system_dir=os.getcwd()
for fname in os.listdir(system_dir):
    if fname.startswith('report'):
        os.remove(os.path.join(system_dir, fname))

這個的做用就是刪除該目錄下,以report開頭的文件,chrome

os.path

os.path.join

主要用到了將兩個路徑合併爲一個路徑,爲何不能用路徑A+路徑B呢?
由於,os.path.join(A,B)會自動根據系統環境,改變兩個路徑的鏈接符。
Windows系統路徑之間是\,而Linux系統路徑是/,所以用os.path.join寫出的程序兼容性就更好了。

os.path.dirname 獲取文件目錄

os.path.dirname(__file__)返回腳本的路徑,可是須要注意一下幾點:

  1. 必須是實際存在的.py文件,若是在命令行執行,則會引起異常NameError: name '__file__' is not defined
  2. 在運行的時候若是輸入完整的執行的路徑,則返回.py文件的全路徑如:
    python c:/test/test.py 則返回路徑c:/test,若是是python test.py則返回空。
  3. 結合os.path.abspath用,效果會好,若是你們看過一些python架構的代碼的話,會發現。

常常有這樣的組合:

  • os.path.abspath(os.path.dirname(__file__))
  • os.path.dirname(os.path.abspath(__file__))

返回的是.py文件的絕對路徑,這就是os.path.dirname(__file__)的用法,其主要總結起來有:
一、不要已命令行的形式來進行os.path.dirname(__file__)這種形式來使用這個函數
二、結合os.path.abspath()使用

參考

pdir2

查看對象的所有屬性和方法,顯示效果比 dir 方法好:

pip install pdir2
>>> import pdir,requests
>>> pdir(requests)

pipreqs

pip freeze 導出當前環境中全部的 python 庫列表:

$ pip install pipreqs
$ pipreqs /home/project/location

pyperclip

Python 剪貼板:

pip install pyperclip  
from pyperclip import copy, paste 

copy('2333') # 向剪貼板寫入 2333 

paste() # 值爲剪貼板中的內容

pypi_simple

解析 Pip 源信息

# "PYPI_URL": "http://pypi.michael.huawei.com/iaas/product/+simple/"
from pypi_simple import PyPISimple
client = PyPISimple(endpoint=pypi_url)
packages = client.get_project_files(whl_project)

rpmUtils

解析 rpm 包名

pkg_name = "java-1.7.0-openjdk-headless-1.7.0.75-2.5.4.2.x86_64.rpm"
(name, version, release, epoch, arch) = splitFilename(pkg_name)

sys

sys.argv

# 讀取配置文件中的參數
try:
    config = sys.argv[1]
except IndexError as e:
    print(u'運行腳本時,請加上cfg參數!', e)
    sys.exit(-1)
print(config)

能夠讀取命令窗口的參數,例如python get_report.py maps.cfg
那麼,這裏sys.argv[1]得到的值就是maps.cfg

sh

Python Shell

pip install sh
from sh import ifconfig
print(ifconfig("eth0"))
from sh import *
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')

shutil

shutil.copyfile( src, dst)    從源src複製到dst中去。固然前提是目標地址是具有可寫權限。拋出的異常信息爲IOException. 若是當前的dst已存在的話就會被覆蓋掉
shutil.move( src, dst)        移動文件或重命名
shutil.copymode( src, dst)    只是會複製其權限其餘的東西是不會被複制的
shutil.copystat( src, dst)    複製權限、最後訪問時間、最後修改時間
shutil.copy( src, dst)        複製一個文件到一個文件或一個目錄
shutil.copy2( src, dst)        在copy上的基礎上再複製文件最後訪問時間與修改時間也複製過來了,相似於cp –p的東西
shutil.copy2( src, dst)        若是兩個位置的文件系統是同樣的話至關因而rename操做,只是更名;若是是不在相同的文件系統的話就是作move操做
shutil.copytree( olddir, newdir, True/Flase)
把olddir拷貝一份newdir,若是第3個參數是True,則複製目錄時將保持文件夾下的符號鏈接,若是第3個參數是False,則將在複製的目錄下生成物理副原本替代符號鏈接
shutil.rmtree( src )    遞歸刪除一個目錄以及目錄內的全部內容

shutil.copy2

print('*'*20+u'轉存源數據文件到結果日期文件夾'+'*'*20)
shutil.copy2(data_source_path, result_file_path)
shutil.copy2(case_source_path, result_file_path)
print('*'*20+u'存儲成功!'+'*'*20)

用來拷貝文件,複製到目標文件夾。

shutil.rmtree

shutil.rmtree('maps',ignore_errors=True)

只有機上後邊的參數,空目錄纔會刪除,不然會報錯。

參考:

types

相似dict/int等一些內置的類型,types模塊已再也不提供了,例如tyopes.IntType已經提供了。

參考:

tenacity

重試:

pip install tenacity 
#限制重試次數爲3次
from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
def extract(url):
    info_json = requests.get(url).content.decode()
    info_dict = json.loads(info_json)
    data = info_dict['data']
    save(data)

uuid

生成通用惟一標識符(Universally Unique ID,UUID)的一種快速簡單方法就是使用 Python 標準庫的 uuid 模塊。

uuid 模塊:https://docs.python.org/3/library/uuid.html

import uuid
user_id = uuid.uuid4()
print(user_id)

wget

提取數據,特別是從網絡中提取數據是數據科學家的重要任務之一。Wget 是一個免費的工具,用於以非交互式方式從 Web 上下載文件。它支持 HTTP、HTTPS 和 FTP 協議,經過 HTTP 代理進行檢索。因爲它是非交互式的,即便用戶沒有登陸,它也能夠在後臺工做。因此,若是你想下載一個網站或一個頁面上的全部圖片,wget 會幫助你。

安裝:

$ pip install wget

示例:

import wget
url = 'http://www.futurecrew.com/skaven/song_files/mp3/razorback.mp3'
filename = wget.download(url)
100% [................................................] 3841532 / 3841532
filename
'razorback.mp3'

YAML

YAML 表明 『YAML Ain』t Markup Language』。它是一種數據格式語言,是 JSON 的超集。

與 JSON 不一樣,它能夠存儲更復雜的對象並引用本身的元素。你還能夠編寫註釋,使其尤爲適用於編寫配置文件。

PyYAML 模塊(https://pyyaml.org/wiki/PyYAMLDocumentation)可讓你在 Python 中使用 YAML。安裝:

$ pip install pyyaml

而後導入到項目中:

import yaml

functools

Remark,作Python PPT工具。

six

python2和python3通用性兼容性封裝,openstack中使用,強烈推薦

requests

建議掌握

eventlet

協程的經典,下層使用的greenlet,建議掌握

greenlet

很是高效的協程封裝,想了解協程機制的話,能夠深刻學習

pycrypto 安全

提供了幾乎全部的加解密算法,下層使用的是cryptograph,建議作基本瞭解

SQLAlchemy

對SQL語句的封裝,建議概念瞭解

Mock

測打樁,建議掌握

Unittest

建議掌握

Multiprocessing

多進程,建議基本瞭解,工做中不經常使用

Threading

多線程,建議掌握,不建議使用thread(thread在python3中變爲內部庫_thread)

Queue

多進程/多線程隊列按序執行的場景,基本瞭解

Subprocess

用於建立新進程,可用於python調用shell/bash等,建議掌握。python調用shell/bash不建議os.system/commands.*(這些方式在python3已經移除)。

Profile/cProfile

用於性能分析,很是很是好用,和pstat配合食用,建議掌握。

時間模塊相關

arrow

Delorean

開發工具

HTTPie

是命令行HTTP客戶端。其目標是使與Web服務的CLI交互儘量人性化。它提供了一個簡單的http命令,容許使用簡單天然的語法發送任意HTTP請求,並顯示彩色輸出。HTTPie可用於測試,調試以及一般與HTTP服務器交互。

GitHub:https://github.com/jakubroztocil/httpie

Linux

paramiko

只要是稍微搞過Python與linux的都會熟悉paramiko這個犀利的庫。
它完美的契合的用戶操做linux機器下的全部操做,ssh ftp等等…

運維

Ansible

是一個極其簡單的IT自動化系統。它處理配置管理,應用程序部署,雲配置,臨時任務執行和多節點編排 – 包括經過負載平衡器輕鬆實現零停機滾動更新等操做。

GitHub:https://github.com/ansible/ansible

Sentry

從根本上講是一項服務,能夠幫助您實時監控和修復崩潰。服務器端使用Python,但它包含一個完整的API,支持在任何應用程序中使用任何語言發送事件。

GitHub:https://github.com/getsentry/sentry

Luigi

是一個Python包,可用來建立複雜的批處理做業管道。可用來處理依賴項解析、工做流管理、可視化、處理故障、命令行集成等等。

GitHub:https://github.com/spotify/luigi

好玩的工具

sh

pip install sh

Progressbar

Progressbar 是 Python 中的一個文本進度條程序庫,用於展現長時間運行操做的過程,從視覺上提示你程序的處理進度。

colorama

YouTube-dl

油管搬運工,可從youtube.com或其餘視頻平臺下載視頻。

GitHub:https://github.com/rg3/youtube-dl

You-Get

是一個小型命令行實用程序,用於從Web下載媒體內容(視頻,音頻,圖像),尤爲是在手邊沒有合適工具的時候。

GitHub:https://github.com/soimort/you-get

參考

相關文章
相關標籤/搜索