Python and Libraries Cheatsheet =============================== Sum --- ``` sum() ``` Profile ------- ``` import pycallgraph graph = pycallgraph.output.GraphvizOutput() graph.output_file = whith pycallgraph.PyCallGraph(output=graph): ``` SQLite ------ ``` import sqlite3 db = sqlite3.connect() ``` ### Read ``` cursor = db.execute() if cursor: cursor.() db.close() ``` ### Write ``` db.execute() db.commit() ``` Curses ------ ``` import curses def main(): curses.wrapper(draw) def draw(screen): screen.clear() screen.addstr(0, 0, "Press ESC to quit.") while screen.getch() != 27: pass ``` Regex ----- ``` import re re.sub(, , ) re.search(, ) ``` Threading --------- ``` import threading ``` ### Thread ``` thread = threading.Thread(target=, args=(, )) thread.start() thread.join() ``` ### Lock ``` lock = threading.Rlock() lock.acquire() lock.release() ``` Bottle ------ ``` import bottle ``` ### Run ``` bottle.run(host='localhost', port=8080) bottle.run(host='0.0.0.0', port=80, server='cherypy') ``` ### Static request ### Dynamic request ### REST request Type ---- ``` type() is int/str/set/list ``` ``` import numbers isinstance(, numbers.Number) ``` Arguments --------- ``` import sys sys.argv ``` Enumerate --------- ``` for i, in enumerate() ``` System Commands --------------- ### Read File ``` with open(, encoding='utf-8') as file: return file.readlines() ``` ### Write to File ``` with open(, 'w', enconding='utf-8') as file: file.write() ``` ### Execute Command ``` import os os.popen().read() ``` JSON ---- ``` import json ``` ### Read File ``` with open(, encoding='utf-8') as file: return json.load(file) ``` ### Write to File ``` with open(, 'w', enconding='utf-8') as file: file.write(json.dumps()) ``` Datetime -------- ``` import datetime now = datetime.datetime.now() now.strftime('%Y%m%d') now.strftime('%Y%m%d%H%M%S') ``` String ------ ``` str.replace(, , ) .isnumeric() ``` Enum ---- ``` import enum class (enum.Enum): = ``` Copy ---- ``` import copy copy.copy() copy.deepcopy() ``` Infinity -------- ``` float("inf") ``` Plot ---- ``` import matplotlib matplotlib.pyplot.plot(, ...) matplotlib.pyplot.show() matplotlib.pyplot.savefig() ``` List ---- ``` [::] ``` Lambda ------ ``` lambda , : lambda: ``` [For] ----- ``` [i+1 for i in range(10)] [i+1 for i in range(10) if i > 5] [i+j for i in range(10) for j in range(10)] ``` Class ----- ``` class : def __init__(self, ): self.a = def __repr__(self): return str({'a': self.a}) def __str__(self): return str(self.a) ``` Random ------ ``` import random random.random() random.randint(, ) random.shuffle() ``` Range ----- ``` range() range(, ) range(, , ) # Negative step for backward ``` List ---- ``` .sort() .reverse() .extend() ``` Print ----- ``` print(, , end='', sep='', file=) ``` Format ------ ``` '{}'.format() ``` ``` {:} -> ' ' {:>} -> ' ' {:^} -> ' ' {:_} -> '____' {:.} -> '' {:.} -> ' ' {:.f} -> ' 3.14' ``` Text Wrap --------- ``` import textwrap textwrap.wrap(, ) ``` Dictionary ---------- .items() .get(, ) .setdefault(, ) ```