Python cheatsheet

Published: July 09, 2020

Python cheatsheet. I.E. setting up a provisionary HTTP Server.

This cheatsheet is a small collection of handy snippets for quick reference in tricky situations. Feel free to suggest edits, propose additions, complain about something, disagree with content or such and the like. Every feedback is a welcome one.

Collection types

my_list = ["an item", "another item", "A third item. Can you believe it?"]
my_tuple = ("this", "will be", "unchangeable")
my_set = {"the order", "of these", "are not guaranteed"}
my_dictionary = { "key1": "Value 1", "Key 2": 42 }

Lists and Tuples are 'ordered'. Items will appear as they are inserted

Sets and Dictionaries are not ordered collection types

Retrieving device hostname

import socket

HOSTNAME = socket.gethostname()

Parse & Dump a JSON file

import json

with open('/path/to/file.json', "r") as f:
    file_contents = json.loads( )
    print( json.dumps(file_contents, indent=4) )

Write to file

with open('/path/to/file.txt', "w") as f:
    f.write( "A string, dumped JSON or the like" )

Get environment variable

import os

variable = os.environ['some_variable_name']

Execute a shell script

import subprocess
subprocess.Popen("", shell=True)

Note: os.system("") is not recommended

Run another Python script

Runs another Python script in the same process as the script executing the command


Dict comprehension

[print(key, value) for key, value in some_dictionary.items()]

Quick HTTP server

Establish a provisionary web server

python -m http.server # for Python 3

Quick HTTP server (Script)

import http.server
import socketserver
import cgi
import webbrowser

PORT = 8787
# Binds to localhost only. "" for exposing this to network interfaces
HOST = "localhost" 

# Launches the default web browser Opens the directory
url = 'http://' + HOST + ":" + str(PORT)

# Magic
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer((HOST, PORT), Handler) as httpd:
    print("serving at port", PORT)

Convert CSV to JSON

import csv
import json

csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')

fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)

Generate uuids

import uuid

nbr = int(input("How many? "))

for _ in range(nbr):

Token authorization with Requests

import requests
import json

TOKEN = "1234longtoken"
URL= ""

headers_dict = {'Authorization': 'token %s' % TOKEN}
r = requests.get(URL, headers=headers_dict)
r_dict = r.json()
r_json = json.dumps(r_dict)


Christoffer Lybekk

Developer under development

Explore more articles with similar tags


Article stats




1 minread time