message.py :  » Web-Services » python-xmltv » pytvgrab-lib-0.5.1 » lib » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Web Services » python xmltv 
python xmltv » pytvgrab lib 0.5.1 » lib » message.py
#!/usr/bin/env python
# -----------------------------------------------------------------------
# Copyright (C) 2003 Chris Ottrey.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MER-
# CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
# -----------------------------------------------------------------------
#
# This code is part of the pytvgrab project:
#    http://pytvgrab.sourceforge.net
#
# -----------------------------------------------------------------------
# Subversion Information, do not edit
#
# $Rev: 258 $
# $LastChangedDate: 2004-11-13 16:45:05 +1100 (Sat, 13 Nov 2004) $
# $LastChangedRevision: 258 $
# $LastChangedBy: ottrey $
#
# $Log: $
#
"""Messaging service"""

DEBUG=1

import sys, os
import i18n
import enum
import output
from output import red,green,blue,turquoise,yellow,purple,bold

# keep this to help gettext extract strings for us:
levels_name=[_( 'ERROR' ), _( 'QUIET' ), _( 'WARNING' ),
             _( 'INFO' ), _( 'MOREINFO' ), _( 'DEBUG' ) ]
levels=[ 'ERROR', 'QUIET', 'WARNING',
         'INFO', 'MOREINFO', 'DEBUG' ]
color_map={ "ERROR": red,
            "QUIET": blue,
            "WARNING": yellow,
            "INFO": turquoise,
            "MOREINFO": bold,
            "DEBUG": purple }

verbose_level=enum.Enum(levels)

verbose=verbose_level.INFO

from grabexceptions import ParseError

import config_locale
from config_locale import LC_ALL,encoding,toprint

def get_value(a):
  result=None
  if a in verbose_level.values():
    result=verbose_level.__dict__[a]
  else:
    raise Exception('Invalid value for verbose: %s\nis not one of %s' %
                       (repr(a), verbose_level.values()))
  return result
# get_value()

def message(msg, vl=verbose_level.INFO):
  """
  Internal message handling
  """
  if verbose != None:
    if  verbose >= vl:
      level = toprint( _( verbose_level[ vl ] ) )
      if level:
        color = color_map[ verbose_level[ vl ] ]
        sys.stderr.write( color( level ) + ': ' )
      msg = toprint( msg )
      sys.stderr.write( msg + '\n' )
# message()

# Or you could use these.
def error( msg ):
  message(msg, verbose_level.ERROR)
  if DEBUG:
    import traceback
    traceback.print_exc()
# error()


def warning (msg): message(msg, verbose_level.WARNING)
def info    (msg): message(msg, verbose_level.INFO)
def moreinfo(msg): message(msg, verbose_level.MOREINFO)
def debug   (msg): message(msg, verbose_level.DEBUG)


def exception( e, indent=0 ):
  TABSPACE="   "
  if isinstance( e, UnicodeError ):
    start = e.start - 40
    end   = e.end + 40
    if start < 0:
      start = 0
    if end > len( e.object ):
      end = len( e.object )
    text = e.object[ start : end ]
    tabs = TABSPACE * indent
    error( ( tabs + _( "Unicode Error:\n" ) +
             tabs + _( "   Encoding: %s\n" ) +
             tabs + _( "   Reason..: %s\n" ) +
             tabs + _( "   String slice:\n%r\n" ) ) %
           ( e.encoding, e.reason, text ) )
  elif isinstance( e, ParseError ):
    error( ( TABSPACE * indent ) +
           _( "Parse Error: %s" ) % e.args[ 0 ] )
    if e.exception: # ParseError was caused by another exception
      exception( e.exception, indent )
    if e.contents:
      debug( "-" * 70 )
      debug( e.contents )
      debug( "-" * 70 )
  elif hasattr( e, 'args' ):
    error( ( TABSPACE * indent ) + _( "Got exception: %s" ) % e.args[ 0 ] )
  else:
    # Some exceptions does not have any args
    # (for example HTMLParser.HTMLParseError)
    error( ( TABSPACE * indent ) + _( "Got exception: %s" ) % repr(e) )
# exception()


# --------------  Unit Tests  -------------- #
using_unittest2=False
try:
  import unittest2 as unittest
  using_unittest2=True
except:
  import unittest

class message_UnitTest(unittest.TestCase):
  def test01(self): v=get_value('ERROR')   ; assert v == verbose_level.ERROR, v
  def test02(self): v=get_value('WARNING') ; assert v == verbose_level.WARNING, v
  def test03(self): v=get_value('INFO')    ; assert v == verbose_level.INFO, v
  def test04(self): v=get_value('MOREINFO'); assert v == verbose_level.MOREINFO, v

if using_unittest2 or __name__ == '__main__':
  unittest.main()
# --------------  Unit Tests  -------------- #
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.