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 setup.py build_ext --inplace

Get cmd parameter: 

sys.argv[1+]

Get absolute path: 

os.path.abspath(relativePath)

 

Get file parent folder: 

os.path.dirname(filePath)

 

Get list of directory files (just file names):

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

Delete file

os.remove(file)

 

Delete (non-empty) folder:

shutil.rmtree(path)

 

Create folders for a given path:

os.makedirs('/path/non-existing/dir/here')

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; 
datetime.datetime.now()

Check if x seconds has passed

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

Clear terminal

import os; 
os.system('clear')

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 
try:     
   failing_code() 
except:     
   tb = traceback.format_exc()

Execute a terminal command (and see output on screen)

os.system("ls")

Execute a command and inspect its output/errors:

import subprocess
result = subprocess.check_output(
 "jnml LEMS_test.xml -neuron; exit 0",
 stderr=subprocess.STDOUT,
 shell=True)
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:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s