Python Cheat Sheet

Create Anaconda environment

conda create -n envName python=2.7

Change Anaconda Python environment

*NIX: source activate p2/p3
WIN: activate p2/3/pb35

Cython re-build files

python build_ext --inplace

Get cmd parameter: 


Get absolute path: 



Get file parent folder: 



Get list of directory files (just file names):

os.listdir(dirPath) # note no os.path

Delete file



Delete (non-empty) folder:



Create folders for a given path:


Copy file to dir:

import shutil 
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext

Conditional for/linq-like statement

 [file for file in os.listdir(path) if file.startswith("prefix")]


LINQ like .first(), get first item in the list

next(i for i in list) # Note no brackets

Get current date/time

import datetime;

Check if x seconds has passed

time.time() # gives num secs since unix epoch

Clear terminal

import os; 

Regular expression search

import re 
matches = re.compile('.*?').findall(testString) # find all instances matches[0] # gets the first match
re.compile('.*?').search(testString).groups()[0] # Gets the first group's matching value

Get the error information as a string:

import traceback 
   tb = traceback.format_exc()

Execute a terminal command (and see output on screen)


Execute a command and inspect its output/errors:

import subprocess
result = subprocess.check_output(
 "jnml LEMS_test.xml -neuron; exit 0",
print(result) # Output and errors will be in string

Get the IP address given a domain name:

import socket
socket.gethostbyname("sub.domain.asu") # Returns IP address string

Implement “with resource() as r:” auto-cleanup interface. Add these two methods to the class definition:

def __enter__(self):
    return self

def __exit__(self, exc_type, exc_value, traceback):
    # Cleanup script here

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s