Note
Utility functions.
Module author: Adam Gagorik <adam.gagorik@gmail.com>
Open a file using gzip if necessary.
Parameters: | handle (str) – filename |
---|---|
Returns: | file handle |
Return type: | file |
>>> handle = zhandle('out.dat.gz', 'rb')
Return last n lines of a file. The python version is much faster than a system call. The python version works on gzipped files.
Parameters: | |
---|---|
Returns: | list of lines |
Return type: |
>>> lines = tail('out.dat', 1)
Extract stub and extension from a file object or string.
Parameters: | handle – filename |
---|---|
Returns: | stub and ext |
Return type: | str, str |
>>> stub, ext = splitext('out.dat')
>>> print stub, ext
('out', '.dat')
Load max objs from a pkl file.
Parameters: | |
---|---|
Returns: | list of data |
Return type: |
>>> data = load_pkl('combined.pkl')
Load a set of pkls into a list.
Parameters: | pkls (list of str) – list of filenames |
---|---|
Returns: | nested list of loaded data |
Return type: | list |
>>> pkls = load_pkls(['a.pkl', 'b.pkl'])
Save obj to a pkl file.
Parameters: | obj (object) – python object |
---|---|
Returns: | the file handle |
Return type: | file |
>>> handle = save_pkl(1, 'test.pkl')
>>> handle = save_pkl(2, handle)
Format a string using str.format() and process with regex. kwargs are passed to the format function.
The following regex are used:
match | replace |
---|---|
‘^_’ | ‘’ |
‘_$’ | ‘’ |
‘_.’ | ‘.’ |
Parameters: | s (str) – string to process |
---|---|
Returns: | the formatted string |
Return type: | str |
>>> print format_string('_{name}.{ext}', ext='dat', name='adam')
adam.dat
>>> print format_string('adam_.{ext}', ext='dat')
adam.dat
Format an output file name and then process with regex. If stub is empty, the leading underscore is striped.
Parameters: | |
---|---|
Returns: | formatted filename |
Return type: |
>>> print format_output(stub='systemA', name='fft', ext='txt')
systemA_fft.txt
See also
Compare two dictionaries.
Parameters: | |
---|---|
Returns: | a results dictionary with the output of set operations |
Return type: |
>>> results = compare_dicts({'A' : 1}, {'A' : 2, 'B' : 3})
>>> for key, value in results.iteritems():
... print key, value
size1 1 # size of dict1
size2 2 # size of dict2
union 2 # union of keys (A, B)
inter 1 # intersection of keys (A)
valid False # are they the same?
A (1, 2) # keys that are different and and their values
Compare two lists.
Parameters: | |
---|---|
Returns: | a results dictionary with the output of set operations |
Return type: |
>>> results = compare_lists([1], [1, 2])
>>> for key, value in results.iteritems():
... print key, value
size1 1 # size of list1
size2 2 # size of list2
union 2 # union of items (1, 2)
inter 1 # intersection of items (1)
valid False # are they the same?