Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to catch errors elegantly and keep methods clean?
    primarykey
    data
    text
    <p>I am in the process of writing a small(er) Python script to automate a semi-frequent, long, and error-prone task. This script is responsible for making various system calls - either though os.system or through os.(mkdir|chdir|etc).</p> <p>Here is an example of my code right now:</p> <pre><code>class AClass: def __init__(self, foo, bar, verbose=False, silent=False): # Sets up variables needed for each instance, etc self.redirect = '' if silent: self.redirect = '&gt; 2&gt;&amp;1' self.verbose = verbose def a_method(self): """ Responsible for running 4-6 things via system calls as described """ if self.verbose and not self.silent: print "Creating a directory" try: os.mkdir('foobar') except OSError, e: raise OSError, "Problem creating directory %s: %s" % (e.filename, e.strerror) if self.verbose and not self.silent: print "Listing a directory" if (os.system('ls foobar %s') % self.redirect) is not 0: raise OSError, "Could not list directory foobar" def b_method(self): """ Looks very similar to a_method() """ def run(self): """ Stitches everything together """ try: a_method() except OSError, e: print "a_method(): %s" % e.strerror sys.exit(-1) try: b_method() except OSError, e: print "b_method(): %s" % e.strerror sys.exit(-1) </code></pre> <p>Obviously writing all the <code>if self.verbose and not self.silent</code> is messy and then the <code>try/catch</code> or <code>if</code> around each call is ugly to look at. I would have liked to use Python's logging class and simply have one logging level (verbose) configurable via command line and then I can simple call <code>logger.debug('My message')</code> but I am using Python 2.2 and I do not have access to the <code>logging</code> class.</p> <p><strong>Summary/Base Questions</strong><br> I am using Python 2.2 and I cannot change this. I am running on an ESX 3.0.2 server and I cannot touch it in any other way for the time being.<br> What is the best way to handle error checking and verbose output without tying this logic to your class (which should only do One Thing)?<br> How can I reduce the clutter with something more simple or elegant to look at?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload