You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

338 lines
3.8 KiB

6 years ago
6 years ago
  1. Python and Libraries Cheatsheet
  2. ===============================
  3. Sum
  4. ---
  5. ```
  6. sum(<list>)
  7. ```
  8. Profile
  9. -------
  10. ```
  11. import pycallgraph
  12. graph = pycallgraph.output.GraphvizOutput()
  13. graph.output_file = <filename>
  14. whith pycallgraph.PyCallGraph(output=graph):
  15. <code>
  16. ```
  17. SQLite
  18. ------
  19. ```
  20. import sqlite3
  21. db = sqlite3.connect(<filename>)
  22. ```
  23. ### Read
  24. ```
  25. cursor = db.execute(<query>)
  26. if cursor:
  27. cursor.<fetchone/fetchall>()
  28. db.close()
  29. ```
  30. ### Write
  31. ```
  32. db.execute(<query>)
  33. db.commit()
  34. ```
  35. Curses
  36. ------
  37. ```
  38. import curses
  39. def main():
  40. curses.wrapper(draw)
  41. def draw(screen):
  42. screen.clear()
  43. screen.addstr(0, 0, "Press ESC to quit.")
  44. while screen.getch() != 27:
  45. pass
  46. ```
  47. Regex
  48. -----
  49. ```
  50. import re
  51. re.sub(<regex>, <new>, <text>)
  52. re.search(<regex>, <text>)
  53. ```
  54. Threading
  55. ---------
  56. ```
  57. import threading
  58. ```
  59. ### Thread
  60. ```
  61. thread = threading.Thread(target=<function>, args=(<first arg>, ))
  62. thread.start()
  63. thread.join()
  64. ```
  65. ### Lock
  66. ```
  67. lock = threading.Rlock()
  68. lock.acquire()
  69. lock.release()
  70. ```
  71. Bottle
  72. ------
  73. ```
  74. import bottle
  75. ```
  76. ### Run
  77. ```
  78. bottle.run(host='localhost', port=8080)
  79. bottle.run(host='0.0.0.0', port=80, server='cherypy')
  80. ```
  81. ### Static request
  82. ### Dynamic request
  83. ### REST request
  84. Type
  85. ----
  86. ```
  87. type(<el>) is int/str/set/list
  88. ```
  89. ```
  90. import numbers
  91. isinstance(<el>, numbers.Number)
  92. ```
  93. Arguments
  94. ---------
  95. ```
  96. import sys
  97. sys.argv
  98. ```
  99. Enumerate
  100. ---------
  101. ```
  102. for i, <el> in enumerate(<list>)
  103. ```
  104. System Commands
  105. ---------------
  106. ### Read File
  107. ```
  108. with open(<filename>, encoding='utf-8') as file:
  109. return file.readlines()
  110. ```
  111. ### Write to File
  112. ```
  113. with open(<filename>, 'w', enconding='utf-8') as file:
  114. file.write(<text>)
  115. ```
  116. ### Execute Command
  117. ```
  118. import os
  119. os.popen(<command>).read()
  120. ```
  121. JSON
  122. ----
  123. ```
  124. import json
  125. ```
  126. ### Read File
  127. ```
  128. with open(<filename>, encoding='utf-8') as file:
  129. return json.load(file)
  130. ```
  131. ### Write to File
  132. ```
  133. with open(<filename>, 'w', enconding='utf-8') as file:
  134. file.write(json.dumps(<object>))
  135. ```
  136. Datetime
  137. --------
  138. ```
  139. import datetime
  140. now = datetime.datetime.now()
  141. now.strftime('%Y%m%d')
  142. now.strftime('%Y%m%d%H%M%S')
  143. ```
  144. String
  145. ------
  146. ```
  147. str.replace(<text>, <old>, <new>)
  148. <str>.isnumeric()
  149. ```
  150. Enum
  151. ----
  152. ```
  153. import enum
  154. class <name>(enum.Enum):
  155. <value> = <index>
  156. ```
  157. Copy
  158. ----
  159. ```
  160. import copy
  161. copy.copy(<object>)
  162. copy.deepcopy(<object>)
  163. ```
  164. Infinity
  165. --------
  166. ```
  167. float("inf")
  168. ```
  169. Plot
  170. ----
  171. ```
  172. import matplotlib
  173. matplotlib.pyplot.plot(<data>, ...)
  174. matplotlib.pyplot.show()
  175. matplotlib.pyplot.savefig(<filename>)
  176. ```
  177. List
  178. ----
  179. ```
  180. <list>[<inclusive from>:<exclusive to>:<step size>]
  181. ```
  182. Lambda
  183. ------
  184. ```
  185. lambda <arg1>, <arg2>: <return value>
  186. lambda: <return value>
  187. ```
  188. [For]
  189. -----
  190. ```
  191. [i+1 for i in range(10)]
  192. [i+1 for i in range(10) if i > 5]
  193. [i+j for i in range(10) for j in range(10)]
  194. ```
  195. Class
  196. -----
  197. ```
  198. class <name>:
  199. def __init__(self, <arg>):
  200. self.a = <arg>
  201. def __repr__(self):
  202. return str({'a': self.a})
  203. def __str__(self):
  204. return str(self.a)
  205. ```
  206. Random
  207. ------
  208. ```
  209. import random
  210. random.random()
  211. random.randint(<from inclusive>, <to inclusive>)
  212. random.shuffle(<list>)
  213. ```
  214. Range
  215. -----
  216. ```
  217. range(<to exclusive>)
  218. range(<from inclusive>, <to exclusive>)
  219. range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward
  220. ```
  221. List
  222. ----
  223. ```
  224. <list>.sort()
  225. <list>.reverse()
  226. <list>.extend(<list>)
  227. ```
  228. Print
  229. -----
  230. ```
  231. print(<el1>, <el2>, end='', sep='', file=<file>)
  232. ```
  233. Format
  234. ------
  235. ```
  236. '{}'.format(<el>)
  237. ```
  238. ```
  239. {:<min width>} -> '<el> '
  240. {:><min width>} -> ' <el>'
  241. {:^<min width>} -> ' <el> '
  242. {:_<min width>} -> '<el>____'
  243. {:.<max width>} -> '<e>'
  244. {:<max widht>.<min width>} -> ' <e>'
  245. {:<max width>.<no of decimals>f} -> ' 3.14'
  246. ```
  247. Text Wrap
  248. ---------
  249. ```
  250. import textwrap
  251. textwrap.wrap(<text>, <width>)
  252. ```
  253. Dictionary
  254. ----------
  255. <dict>.items()
  256. <dict>.get(<key>, <default>)
  257. <dict>.setdefault(<key>, <default>)
  258. ```