Monthly Archives: October 2008

This is an old trick i had lost track of since i last used it. It resurfaced with the need in another program that i was writing and thought it apt to share it, and record it for my reference.  It is fairly simple. But i would summarize it before we go to the script.

  • Create a class to pass the instance of the stdout/stderr. Here i have chose to pass stderr.
  • Open the log file to which the stderr messages need to be recorded to- should be done in the constructor.
  • And then override the write method so that it writes both to the stderr and to the file.

Now you are basically done. See the follow code.

import sys

class logstderr:
    """
    logstderr class is used to log any output that
    is directed to the screen
    """
    def __init__(self, wrfile):
        """
        logstderr constructor
        takes the stream that needs to be logged
        """
        self.wrfile = wrfile
        self.log = file("log.log","w+")

    def write(self, str):
        """
        To override the write of
        sys.stderr.write
        """
        self.wrfile.write(str)
        self.log.write(str)

    def __del__(self):
        self.log.close()

if __name__=="__main__":
    lg =  logstderr(sys.stderr)
    sys.stderr = lg

    print >>sys.stderr,"Hello"
    print >>sys.stderr,"World!"

Many will be surprised that such a user friendly language as python does not provide something a like a switch-case. Wow! Isn’t that something that should come with the language by default. Why did python not opt it in? You could read this chain. But all the more reason to read this article to get around this inability and like all thing in python this too is fairly simple. You would kick yourself for not figuring out. I would put the code in first… here!

def madrid():
  print "Welcome to Madrid"

def geneva():
  print "Welcome to Geneva"

def hawaii():
  print "Welcome to Hawaii"

def unknown():
  print "I cannot take you there. Sorry!"

#destinations = {"madrid":madrid,"geneva":geneva,"hawaii":hawaii}
#incorporating drj11's suggestions for he feels awkward and its true.
#Thanks drj11
destinations = dict(madrid=madrid,geneva=geneva,hawaii=hawaii)

destination =  raw_input("Where do you want to go today? ")
destinations.get(destination,unknown)()

Two things that you need to take care while using the above given method

  1. Always create your dictionary after the function definition. You check out what happens if you dont do  that :)
  2. Make sure sure you pass the second argument to the dict.get method as this works like the “default” case of your standard switch statement.

The code is pretty straightforward and needs no explanation.