API¶
Context managers¶
-
pmisc.ignored(*exceptions)¶ Execute commands and selectively ignore exceptions.
Inspired by “Transforming Code into Beautiful, Idiomatic Python” talk at PyCon US 2013 by Raymond Hettinger.
Parameters: exceptions (Exception object, i.e. RuntimeError, OSError, etc.) – Exception type(s) to ignore For example:
# pmisc_example_1.py from __future__ import print_function import os, pmisc def ignored_example(): fname = 'somefile.tmp' open(fname, 'w').close() print('File {0} exists? {1}'.format( fname, os.path.isfile(fname) )) with pmisc.ignored(OSError): os.remove(fname) print('File {0} exists? {1}'.format( fname, os.path.isfile(fname) )) with pmisc.ignored(OSError): os.remove(fname) print('No exception trying to remove a file that does not exists') try: with pmisc.ignored(RuntimeError): os.remove(fname) except: print('Got an exception')
>>> import docs.support.pmisc_example_1 >>> docs.support.pmisc_example_1.ignored_example() File somefile.tmp exists? True File somefile.tmp exists? False No exception trying to remove a file that does not exists Got an exception
-
class
pmisc.Timer(verbose=False)¶ Bases: object
Time profile of code blocks.
The profiling is done by calculating elapsed time between the context manager entry and exit time points. Inspired by Huy Nguyen’s blog.
Parameters: verbose (boolean) – Flag that indicates whether the elapsed time is printed upon exit (True) or not (False) Returns: pmisc.Timer Raises: RuntimeError (Argument `verbose` is not valid) For example:
# pmisc_example_2.py from __future__ import print_function import pmisc def timer(num_tries, fpointer): with pmisc.Timer() as tobj: for _ in range(num_tries): fpointer() print('Time per call: {0} seconds'.format( tobj.elapsed_time/(2.0*num_tries) )) def sample_func(): count = 0 for num in range(0, count): count += num
>>> from docs.support.pmisc_example_2 import * >>> timer(100, sample_func) Time per call: ... seconds
-
elapsed_time¶ Returns elapsed time (in milliseconds) between context manager entry and exit time points
Return type: float
-
-
class
pmisc.TmpDir(dpath=None)¶ Bases: object
Create a temporary (sub)directory.
Parameters: dpath (string or None) – Directory under which temporary (sub)directory is to be created. If None the (sub)directory is created under the default user’s/system temporary directory Returns: temporary directory absolute path Raises: RuntimeError (Argument `dpath` is not valid) Warning
The file name returned uses the forward slash (
/) as the path separator regardless of the platform. This avoids problems with escape sequences or mistaken Unicode character encodings (\\userfor example). Many functions in the os module of the standard library ( os.path.normpath() and others) can change this path separator to the operating system path separator if needed
-
class
pmisc.TmpFile(fpointer=None, *args, **kwargs)¶ Bases: object
Creates a temporary file that is deleted at context manager exit.
The context manager can optionally set up hooks for a provided function to write data to the created temporary file.
Parameters: - fpointer (function object or None) – Pointer to a function that writes data to file. If the argument is not None the function pointed to receives exactly one argument, a file-like object
- args (any) – Positional arguments for pointer function
- kwargs (any) – Keyword arguments for pointer function
Returns: temporary file name
Raises: RuntimeError (Argument `fpointer` is not valid)
Warning
The file name returned uses the forward slash (
/) as the path separator regardless of the platform. This avoids problems with escape sequences or mistaken Unicode character encodings (\\userfor example). Many functions in the os module of the standard library ( os.path.normpath() and others) can change this path separator to the operating system path separator if neededFor example:
# pmisc_example_3.py from __future__ import print_function import pmisc def write_data(file_handle): file_handle.write('Hello world!') def show_tmpfile(): with pmisc.TmpFile(write_data) as fname: with open(fname, 'r') as fobj: lines = fobj.readlines() print('\n'.join(lines))
>>> from docs.support.pmisc_example_3 import * >>> show_tmpfile() Hello world!
File¶
-
pmisc.make_dir(fname)¶ Create the directory of a fully qualified file name if it does not exist.
Parameters: fname (string) – File name Equivalent to these Bash shell commands:
$ fname="${HOME}/mydir/myfile.txt" $ dir=$(dirname "${fname}") $ mkdir -p ${dir}
Parameters: fname (string) – Fully qualified file name
-
pmisc.normalize_windows_fname(fname)¶ Fix potential problems with a Microsoft Windows file name.
Superfluous backslashes are removed and unintended escape sequences are converted to their equivalent (presumably correct and intended) representation, for example
r'