Changeset 1003 in lmdz_wrf for trunk


Ignore:
Timestamp:
Aug 11, 2016, 11:44:38 AM (9 years ago)
Author:
lfita
Message:

Adding `Capturing': Class to capture the standard output from a function

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/generic_tools.py

    r999 r1003  
    44import re
    55import numpy.ma as ma
     6from cStringIO import StringIO
     7import sys
    68
    79main = 'nc_var_tools.py'
     
    2426
    2527####### Content
     28# Capturing: Class to capture the standard output from a function
    2629# CFmonthU_daysU: Function to transform from a CF date series with units as 'months since [DATE]' to 'days since [DATE]'
    2730# CFvar_DIAGvar: Function to provide which model diagnostic values can provide a CF-variable from ASCII file
     
    82628265    return dictv
    82638266
     8267class Capturing(list):
     8268    """ Class to capture the standard output from a function
     8269      from: http://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call
     8270      Usage:
     8271
     8272      'output' is now a list containing the lines printed by the function call.
     8273      >>> romdict = {'i': 1, 'ii': 2, 'iii': 3, 'iv': 4, 'v':5, 'vi':6, 'vii':7, 'viii':8, 'ix': 9, 'x':10}
     8274      >>> with Capturing() as output:
     8275      >>>    printing_dictionary(romdict)
     8276      >>> print output
     8277      ['    # i: 1', '    # ii: 2', '    # iii: 3', '    # iv: 4']
     8278    """
     8279    def __enter__(self):
     8280        self._stdout = sys.stdout
     8281        sys.stdout = self._stringio = StringIO()
     8282        return self
     8283    def __exit__(self, *args):
     8284        self.extend(self._stringio.getvalue().splitlines())
     8285        sys.stdout = self._stdout
     8286
    82648287#quit()
    82658288
Note: See TracChangeset for help on using the changeset viewer.