Skip to content

Python cheatsheet

Argparse

#!/usr/bin/env python3

import argparse

def main():
    parser = argparse.ArgumentParser()
    args = parser.parse_args()

if __name__ == '__main__':
    main()

File operations

Read a file

with open('file.txt', 'r') as file:
    content = file.read()
    print(content)

Write to a file

with open('file.txt', 'w') as file:
    file.write('Hello, World!')

Append to a file

with open('file.txt', 'a') as file:
    file.write('\nNew line.')

Execptions

try:
    result = 1 / 0
except ZeroDivisionError:
    print("Division by zero!")

JSON

Load JSON as Python object

import json

json_string = {"a": 1, "b": 2}
data = json.loads(json_string)

Python object as JSON

import json
person = {
    "name": "Alice",
    "city": "New York",
}

json_string = json.dumps(person, indent=4)

PIP

Install package

pip install package-name

Uninstall package

pip uninstall package-name

List installed packages

pip list

Show package information

pip show requests

Install packages from requirements.txt file

pip install -r requirements.txt

Create requirements.txt file

pip freeze > requirements.txt

Networking

HTTP server

python -m SimpleHTTPServer [port]
python3 -m http.server [port]

CGI server

CGI script

#!/usr/bin/env python
import cgi

print 'Content-Type: text/html\n'
print 'hello world'

Start server

python -m CGIHTTPServer 8000 .

SMTP server

Start debug SMTP server - messages are printed to STDOUT and discarded

python -m smtpd -n -c DebuggingServer localhost:1025

Send HTTP request

urllib example:

import urllib2
u = urllib2.urlopen(url)
print u.read()
u.close()

requests example:

import requests

# GET
r1 = requests.get(url)
print r1.status_code
print r1.content

# POST
r2 = requests.post(url, data={'a': 1}, cookies=r1.cookies)
r1.close()
r2.close()

Flask

Simple Flask example

from flask import Flask
import os
import os.path
import sys

from flask import render_template

app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('index.html', person=name)