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")
>>> m.group(0)
'Isaac Newton'
>>> m.group(1)
'Isaac'
>>> m.group(2)
'Newton'
>>> m.group(1,2)
('Isaac', 'Newton')

Resource: https://docs.python.org/2/library/re.html

File operations

Read file line-by-line and print each line

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

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.close()

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

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

os.remove('path/to/file')

List comprehension

This for loop:

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

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

print(list[0])

String interpolation with Python 3.6.x

site = 'https://google.com'
os.system(f"open -a /Applications/Google\ Chrome.app {site}")

Multiline list

list = [
    'item1',
    'item2',
]

Create requirements.txt with pip

pip freeze > requirements.txt

Debugger one-liner

import pdb; pdb.set_trace()

Show global vars in pdb

globals()

Show available methods for an object

dir(object)

Show object type

type(object)

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]
else:
    dict[key].append(value)

Print a dictionary to a table

Just use https://pypi.python.org/pypi/PrettyTable and save yourself a headache.

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

        Usage:
        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 https://github.com/kennethreitz/autoenv, 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/activate.sh

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.