Python cheatsheet
Published 6 months ago: July 09, 2020
Updated: October 14, 2020
Python cheatsheet. I.E. setting up a provisionary HTTP Server.
Index
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.
Generic
Retrieve device hostname
import socket
HOSTNAME = socket.gethostname()
print(HOSTNAME)
Get help for a Class object
help(TheClassObject)
Parse & Dump a JSON file
import json
with open('/path/to/file.json', "r") as f:
file_contents = json.loads( f.read() )
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("script2.sh", shell=True)
#Note: *<code>os.system("script2.sh")</code> is not recommended*
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
Run another Python script
Runs another Python script in the same process as the script executing the command
exec(open("script2.py").read())
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)
webbrowser.open_new_tab(url)
# Magic
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer((HOST, PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
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)
jsonfile.write('\n')
Generate uuids
import uuid
nbr = int(input("How many? "))
for _ in range(nbr):
print(uuid.uuid4())
Token authorization with Requests
import requests
import json
TOKEN = "1234longtoken"
URL= "https://api.github.com/repos/user/repo/releases/latest"
headers_dict = {'Authorization': 'token %s' % TOKEN}
r = requests.get(URL, headers=headers_dict)
r_dict = r.json()
r_json = json.dumps(r_dict)
print(r_json)