好用好玩的Python包


click

最好的實現命令行的方式,它基於optparse。
optparse和argparse是python標准庫,但它們不夠好用。
docopt通過解析注釋來實現命令行。

Fire

無侵入的命令行工具,和click、argparse是同類東西。

ujson

用C++實現的json解析器,速度飛快。

prettytable

在控制台下使用表格展示數據

import prettytable
t=prettytable.PrettyTable(['name','age'])
for i in range(10):
    t.add_row(['user%s'%i,i])
print(t)

tabulate

tabulate包只有一個tabulate函數

data參數

支持打印的數據類型

  • 二維list或者其它二維可迭代對象
  • 一維字典列表,每個字典表示一行
  • 二維numpy數組
  • numpy記錄數組
  • pandas.DataFrame
  • firstrow
  • keys
  • 字符串列表

showindex

  • 布爾值,是否顯示每行的下標
  • rowId列表,手動指定每行的ID

tablefmt

  • "plain"
  • "simple"
  • "github"
  • "grid"
  • "fancy_grid"
  • "pipe"
  • "orgtbl"
  • "jira"
  • "presto"
  • "psql"
  • "rst"
  • "mediawiki"
  • "moinmoin"
  • "youtrack"
  • "html"
  • "latex"
  • "latex_raw"
  • "latex_booktabs"
  • "textile"

參考資料

wget

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

linux和osx的用戶還有其它選擇:from sh import wget。

progressbar

人盡皆知的tqdm就不必多說了,這里說一個更為靈活的進度條

from progressbar import ProgressBar
import time
pbar = ProgressBar(maxval=10)
for i in range(1, 11):
    pbar.update(i)
    time.sleep(1)
pbar.finish()

colorama

向控制台打印彩色文字。這個庫非常簡潔優美,它主要包含四種東西:

  • Fore:設置前景色
  • Back:設置背景色
  • Style:設置字體粗細,分為Bright、DIM、NORMAL、RESET_ALL四種
  • Cursor:控制光標,分為UP,DOWN,FORWARD,BACK,POS五種函數,其中方向函數接受一個參數n,表示移動的格數,POS接受x和y兩個參數表示把光標移動到的位置。
import colorama

colorama.init(True)
print(dir(colorama))
for t in "Fore Back Style".split():
    ty = getattr(colorama, t)
    for i in dir(ty):
        if i.startswith('__'): continue
        print(t, i, getattr(ty, i) + "天下大勢為我所控")

print("haha" + colorama.Cursor.BACK(2) + "baga")  # 輸出habaga

如下代碼展示了顏色打印的原理

class Colorize:
    color_map = {
        'black': 0,
        'red': 1,
        'green': 2,
        'yellow': 3,
        'blue': 4,
        'magenta': 5,
        'cyan': 6,
        'white': 7
    }
    format_buffer = dict(
        bg_color=None,
        text_color=None,
        is_bold=None,
    )

    @classmethod
    def text(cls, color):
        cls.format_buffer['text_color'] = cls.color_map.get(color.lower(), None)
        if cls.format_buffer['text_color'] is not None:
            cls.format_buffer['text_color'] += 30
        return cls

    @classmethod
    def bg(cls, color):
        cls.format_buffer['bg_color'] = cls.color_map.get(color.lower(), None)
        if cls.format_buffer['bg_color'] is not None:
            cls.format_buffer['bg_color'] += 40
        return cls

    @classmethod
    def bold(cls):
        cls.format_buffer['is_bold'] = 1
        return cls

    def __new__(cls, *message, delimiter=' '):
        result = '\033[{}m{}\033[0m'.format(';'.join([str(x) for x in cls.format_buffer.values() if x is not None]),
                                            delimiter.join([str(m) for m in message]))
        cls.format_buffer['text_color'] = None
        cls.format_buffer['bg_color'] = None
        cls.format_buffer['is_bold'] = None
        return result

使用時print(Colorize.text(color)(s))

functools.lru_cache

最近最少使用裝飾器,用於緩存函數運行結果。
此裝飾器接受兩個參數:maxsize和typed。當maxsize=None時,無限存儲;否則maxsize必須是一個int值,表示緩存的參數類型種數。如果typed=True,則緩存認為3.0和3是同一個key。
此裝飾器修飾的函數的參數必須都是可以求哈希值的參數。
如果用此裝飾器修飾f()函數,可通過f.cache_info()查看緩存信息,包括:命中次數,失敗次數,緩存的最大大小,當前緩存大小。
使用f.cache_clear()可以清空緩存。

import functools


@functools.lru_cache(maxsize=2, typed=False)
def haha(x):
    print(haha.__name__, x, 'is called')
    return str(x)


haha(1)
haha(2)
haha(3)
print(haha.cache_info())
haha(1)
haha(3)
haha.cache_clear()
haha(3)

"""輸出
haha 1 is called
haha 2 is called
haha 3 is called
CacheInfo(hits=0, misses=3, maxsize=2, currsize=2)
haha 1 is called
haha 3 is called
"""

在不知道此裝飾器之前,我自己寫過一個同樣功能的裝飾器,但是肯定不如此裝飾器考慮的詳細。

def simple_cache(timeout=3):
    """
    基於內存的緩存
    :param timeout: float 緩存過期的時間,單位為秒
    :return: 返回被裝飾的函數的返回值

    注意事項:
    * 被裝飾的函數的參數必須可以被可序列化為JSON,否則調用出錯
    * 對於參數種類很多的函數,不要使用此裝飾器,否則內存容易爆
    * 此裝飾器適合裝飾
    >>> @simple_cache(timeout=3)
    >>>  def haha(user_id):
    >>>     print("haha", user_id)
    >>> haha(0)# 第一次訪問user_id=0的用戶,調用haha這個函數
    >>> haha(0)#第二次調用user_id=0的用戶,使用緩存,不會調用haha這個函數
    >>> haha(1)#第一次調用user_id=1的用戶,緩存未命中,會調用haha這個函數
    >>> time.sleep(5)
    >>> haha(1)#經過一段時間后,緩存失效,第二次調用user_id=1的用戶緩存未命中,會調用haha這個函數
    """

    def decorator(f):
        def ff(*args, **kwargs):
            arg = json.dumps([args, kwargs])
            res = None
            key = f.__module__ + f.__name__ + arg
            if hasattr(f, key):
                res = getattr(f, key)
                if time.time() - res['last_time'] > timeout:
                    res = None
            if res is None:
                res = {'last_time': time.time(), 'data': f(*args, **kwargs)}
                setattr(f, key, res)
            return res['data']

        return ff

    return decorator

使用git submodules

當一個repo依賴另一個repo,另一個repo無法通過pip安裝時,就需要添加一個.gitmodules文件,文件內容如下:

[submodule "vendor/libbpp"]
	path = vendor/libbpp
	url = git@git-core.megvii-inc.com:SkunkWorks/libbpp.git

使用命令git submodule update --init --recursive可以初始化gitmodule。

使用make命令

一個項目包含的命令可能非常多,而這些命令又非常短,如果每個命令都新建一個.bat或者.sh會顯得非常啰嗦,這時make就派上用場了。在node中,可以通過package.json配置命令,但是那樣只能配置一個命令。make可以把多個長命令用一個短命令替代。

deploy:
	make -j 64 -f Makefile.work deploy

update:
	git pull
	git submodule update --init --recursive
	pip3 install --user -r requirements.txt

簡單的守護進程

supervisor.sh

#!/bin/bash
set -x

while true; do
    date
    "$@"
    sleep 1
done

使用時直接supervisor.sh haha,就可以在haha停止時的下一秒鍾自動運行haha。

pony

pony是一個python orm框架,用戶不必書寫SQL,該框架自動將python語法轉成SQL語句。
Pony is a Python ORM with beautiful query syntax.
https://ponyorm.org/

sendToTrash

兼容多個平台,把文件發送到垃圾桶。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM