root / pykota / trunk / pykota / utils.py @ 3354

Revision 3354, 6.4 kB (checked in by jerome, 16 years ago)

Added a function to return the default charset.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[3260]1# -*- coding: UTF-8 -*-
[695]2#
[3260]3# PyKota : Print Quotas for CUPS
[695]4#
[3275]5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
[3260]6# This program is free software: you can redistribute it and/or modify
[873]7# it under the terms of the GNU General Public License as published by
[3260]8# the Free Software Foundation, either version 3 of the License, or
[873]9# (at your option) any later version.
[3260]10#
[873]11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
[3260]17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[695]18#
19# $Id$
20#
[3294]21
22"""This module defines some utility functions which make no sense as methods."""
23
24import sys
[3295]25import os
[3294]26import locale
27import gettext
[3310]28from types import UnicodeType
[3294]29
[3318]30from pykota.errors import PyKotaCommandLineError
31
[3294]32def initlocale(lang="", cset=None) :
33    """Initializes the locale stuff."""
34    try :
35        locale.setlocale(locale.LC_ALL, (lang, cset))
36    except (locale.Error, IOError) :
37        locale.setlocale(locale.LC_ALL, None)
38    (language, charset) = locale.getlocale()
39    language = language or "C"
40    try :
41        charset = charset or locale.getpreferredencoding()
42    except locale.Error :   
43        charset = sys.stdout.encoding or sys.getfilesystemencoding()
44
[3298]45    if (not charset) or charset in ("ASCII", "ANSI_X3.4-1968") :
[3294]46        charset = "UTF-8"
[3298]47       
[3294]48    return (language, charset)
49
[3298]50def setenv(varname, value, charset) :
51    """Sets an environment variable."""
52    if value is None :
53        value = "None"
54    os.environ[varname] = value.encode(charset, "replace")   
55   
[3294]56def initgettext(lang, cset) :
57    """Initializes gettext translations for PyKota."""
58    try :
59        try :
60            trans = gettext.translation("pykota", \
61                                        languages=["%s.%s" % (lang, 
62                                                              cset)], 
63                                        codeset=cset)
64        except TypeError : # Python <2.4
65            trans = gettext.translation("pykota", 
66                                        languages=["%s.%s" % (lang, 
67                                                              cset)])
68        trans.install(unicode=True)
69    except :
70        gettext.NullTranslations().install(unicode=True)
[3295]71       
72def getpreferredlanguage() :
73    """Returns the preferred language."""
74    languages = os.environ.get("HTTP_ACCEPT_LANGUAGE", "")
75    langs = [l.strip().split(';')[0] for l in languages.split(",")]
76    return langs[0].replace("-", "_")
77   
78def getpreferredcharset() :
79    """Returns the preferred charset."""
80    charsets = os.environ.get("HTTP_ACCEPT_CHARSET", "UTF-8")
81    charsets = [l.strip().split(';')[0] for l in charsets.split(",")]
82    return charsets[0]
[3294]83
[3295]84def reinitcgilocale() :       
85    """Reinitializes the locale and gettext translations for CGI scripts, according to browser's preferences."""
86    initgettext(*initlocale(getpreferredlanguage(), getpreferredcharset()))
87   
88def N_(message) :
89    """Fake translation marker for translatable strings extraction."""
90    return message
91
[3294]92def databaseToUnicode(text) :
[3298]93    """Converts from database format (UTF-8) to unicode.
94   
95       We use "replace" to accomodate legacy datas which may not
96       have been recorded correctly.
97    """
[3294]98    if text is not None :
[3310]99        if not isinstance(text, UnicodeType) :
100            return text.decode("UTF-8", "replace")
101        else :   
102            # MySQL already returns unicode objects
103            return text
[3294]104    else : 
105        return None
106   
107def unicodeToDatabase(text) :
108    """Converts from unicode to database format (UTF-8)."""
109    if text is not None : 
[3298]110        return text.encode("UTF-8")
[3294]111    else :   
112        return None
113           
[3354]114def getdefaultcharset() :           
115    """Returns the default charset to use."""
116    return sys.stdout.encoding or locale.getlocale()[1] or "ANSI_X3.4-1968"
117   
[3294]118def logerr(text) :
119    """Logs an unicode text to stderr."""
[3354]120    sys.stderr.write(text.encode(getdefaultcharset(), "replace"))
[3295]121    sys.stderr.flush()
[3318]122   
[3354]123def loginvalidparam(opt, value, defaultvalue=None, additionalinfo=None) :
[3318]124    """Logs an error when an invalid parameter to a command line option
125       is encountered.
126    """   
[3354]127    message = _("Invalid value '%(value)s' for the %(opt)s command line option") \
[3318]128                                % locals()
[3354]129    if defaultvalue is not None :                           
130        message += ", using default '%(defaultvalue)s' instead" % locals()
[3318]131    if additionalinfo :
132        logerr("%s (%s)\n" % (message, additionalinfo))
133    else :   
134        logerr("%s\n" % message)
[3294]135           
[3295]136def crashed(message="Bug in PyKota") :   
137    """Minimal crash method."""
138    import traceback
139    from pykota.version import __version__
140    lines = []
141    for line in traceback.format_exception(*sys.exc_info()) :
[3354]142        line = line.decode(getdefaultcharset(), "replace")
[3295]143        lines.extend([l for l in line.split("\n") if l])
144    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKota v%s" % __version__, message] + lines)])
145    logerr(msg)
146    return msg
[3318]147   
148def run(optparser, workclass, requireargs=False) :
149    """Runs a PyKota command line tool."""
150    appname = os.path.basename(sys.argv[0])
151    retcode = 0
152    (options, arguments) = optparser.parse_args()                   
153    if requireargs and not arguments :
154        logerr("%s\n" % (_("%(appname)s requires arguments, please use --help") \
155                            % locals()))
156        retcode = -1
[3321]157    application = None   
[3318]158    try :
159        try :
[3321]160            application = workclass()
161            application.deferredInit()
162            retcode = application.main(arguments, options)
163        except KeyboardInterrupt :       
164            logerr("\nInterrupted with Ctrl+C !\n")
165            retcode = -3
166        except PyKotaCommandLineError, msg :   
167            logerr("%s : %s\n" % (sys.argv[0], msg))
168            retcode = -2
169        except SystemExit :       
170            pass
171        except :
172            title = _("%(appname)s failed") % locals()
173            try :
174                application.crashed(title)
175            except :   
176                crashed(title)
177            retcode = -1
178    finally :   
179        try :
180            application.storage.close()
[3318]181        except :   
[3321]182            pass
183           
[3318]184    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.