Python Notes

This will encompass things that I find useful and end up looking up later when I haven't coded in a while.

Python3 Simple HTTP Server

python3 -m http.server <port>

Regex and group matching

>>> import re
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
'Isaac Newton'
('Isaac', 'Newton')


File operations

Read file line-by-line and print each line

def print_lines(file):
    with open(file) as f:
        for line in f:

Read file into list

def return_list(file):
    with open(file) as f:
        list = f.readlines()
        return list

Remove line from a file containing a specified string

def remove_line_containing_string(file):
    f = open(file, 'r')
    contents = f.readlines()

    f = open (file, 'w')
    for line in contents:
        if not 'some string' in line:

List only files in a directory

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

Remove file


List comprehension

This for loop:

for x in range(int(sp),int(ep)+1):

can also be represented as this list comprehension:
[port_scan(site, int(x)) for x in range(int(sp), int(ep)+1)]

Print a line from a list


String interpolation with Python 3.6.x

site = ''
os.system(f"open -a /Applications/Google\ {site}")

Multiline list

list = [

Create requirements.txt with pip

pip freeze > requirements.txt

Debugger one-liner

import pdb; pdb.set_trace()

Show global vars in pdb


Show available methods for an object


Show object type


Remove \n and extra quotes from an object

obj.rstrip().replace('"', '')

Check if current user is root, exit if not

def check_root():
    if not os.geteuid() == 0:
        sys.exit('This script must be run as root!')

Dictionary Notes

Add value to list in dictionary if it doesn't exist; otherwise append the value to the existing list.

if not dict.has_key(key):
    dict[key] = [value]

Print a dictionary to a table

Just use and save yourself a headache.

from prettytable import PrettyTable
def output_dict_to_table(in_dict):
        Print an input dictionary as a table

        output_dict_to_table({'Key': ['Value'], 'Key2': ['Value2', 'Value3']})
        t = PrettyTable(['Key', 'Value'])
        for k, v in in_dict.items():
                t.add_row([k, v])
        print t

Auto enable virtualenv for a directory

Use, which can be installed via brew, pip, etc.

Once it's installed, add this line to your bash_rc or zshrc or whatever (the path will vary based on which installation method you used):
source /usr/local/opt/autoenv/

Once this is done, you simply drop a .env file into the directory which has a virtualenv, that should look like this:
source .venv/bin/activate

Now whenever you cd into this directory, virtualenv will automatically be activated. You will have to deactivate manually when you leave though.

Commenting Standards

A nice example can be found here for google style.