Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
159 lines (127 sloc) 3.37 KB
<!DOCTYPE html>
<meta charset="utf-8" />
<title>Python Cheatsheet</title>
<!--[if IE]>
<script src=""></script>
<link rel=stylesheet href=screen.css>
<h1>Python Cheatsheet</h1>
<p id="toc">&nbsp;</p>
<h2 id=script>Python File</h2>
<h3 id=script-header>Header</h3>
#!/usr/bin/env python
# -*- python -*-
<h3 id=script-main>Script execution</h3>
# at the end of the script
if __name__ == '__main__':
# executed when the script is executed from the shell
<h2 id=file>File I/O</h2>
<h3 id=file-stdin>Read from a file or stdin</h3>
def <mark>file_or_stdin(f)</mark>:
if f == '-':
return sys.stdin
return file(f)
for line in <mark>file_or_stdin(sys.argv[1])</mark>:
print line
<h2 id=http>HTTP</h2>
<h3 id=http-get>GET Request</h3>
import <mark>httplib</mark>
conn = httplib.HTTPConnection(host, port)
conn.request('GET',request, "", headers)
res = conn.getresponse()
if (res.status != 200):
print("HTTP", res.status, res.reason)
out =
<h2 id=xml>XML</h2>
<h3>Get a DOM document from a string</h3>
from <mark>xml.dom import minidom</mark>
xmldoc = minidom.parseString(xml)
<h3 id=xml-elements>Get all elements by tag name</h3>
elements = xmldoc.getElementsByTagName(tagName)
<h3 id=xml-element-text>Get the text of an element</h3>
text = <mark></mark>
<h3 id=xml-attr-value>Get the value of an element's attribute</h3>
value = <mark>element.attributes[name].value</mark>
<h2 id=json>JSON</h2>
<h3 id=json-module>Import JSON module</h3>
import json
except ImportError:
import simplejson as json
<h3 id=json-load>Read a JSON string</h3>
obj = <mark>json.loads(str)</mark>
print obj['id']
print obj['document']['body']
<h2 id=cli>CLI parameters</h2>
<p>Run the script with <kbd>-h</kbd> to display the usage</p>
import <mark>argparse</mark>
parser = argparse.ArgumentParser(description='This script reads data and do other stuff.')
parser.add_argument('-v', '--verbose', required=False, dest='verbose',
help='Print verbose logs',
parser.add_argument('-H', '--host', metavar='HOST', required=True, dest='host',
help='Name of the host of the server.')
parser.add_argument('-o', '--out', metavar='OUTPUT_FILE', required=False, dest='outFile',
help='Name of the output file. Default base is out.txt.')
args = parser.parse_args()
print args.verbose
print args.outFile
<h2 id=pprint>Pretty Print</h2>
import pprint
pp = pprint.PrettyPrinter(indent=4)
&copy; 201 <a href="">Jeff Mesnil</a>
<script src=''></script>
<script src='j/doc.js'></script>