Feed on
Posts
Comments

Archive for the 'Python' Category

let’s say you’ve got a list of the numbers 0 through 4 and you wanted all 32 possible combinations of them.  to get that list:
list_of_five = range(0,5)   
swap_list_list = [[]]
for swap in list_of_five:
    temp_lists = []
    for list_stub in swap_list_list:
        this_list = copy.copy(list_stub)
        this_list.append(swap)
        temp_lists.append(this_list)
temp_lists.append(list_stub)
    swap_list_list = temp_lists
print swap_list_list
 
 

sort a python dictionary

let’s say you’ve got a dictionary keyed by strings and whose values are numbers.  if you’d like to sort those keys by those values, here’s a quick way to do so: my_dict_to_sort.sort(cmp=lambda a,b: cmp(a[1],b[1])) 

when you execute a program in python, the program’s name can be found with the following command: 
import sys 
print sys.argv[0]

 to get the full path to the program, use the abspath command: 
import os 
os.path.abspath(sys.argv[0])
 

to make a file executable from python, use the following template:
 >> import os>> my_filename = “file.txt”>> os.chmod(my_filename,0755)

flush python’s print buffer

to flush the print buffer in python: 
>> sys.stdout.flush() 

real simple: 
>> abs(val) 

to not have the output of subprocess.check_call print out in python, pass the output to /dev/null like so:
subprocess.check_call(angst_call,stdout=open(os.devnull,”w”))

this is almost certainly not the best way to read the output of a python system call.  but, it works.    let’s say i’d like to read the results of a call to ls.  here’s how to do it:
import subprocess
proc = subprocess .Popen([ls],stdout=sub.PIPE)
print proc.stdout.read()

let’s say you want to make an array of all the numbers between 5 and 7, separated by the interval 0.33 in python. one way to do that would be:
min = 5.0
max = 7.0
interval = 0.33
my_list = [min + val*interval for val in range(int((max-min)/interval))]

get timestamp in python

to insert a timestamp into your python code:
import time
….
print time.localtime()

Next »

More blogs about http://desk.stinkpot.org:8080/tricks.