Salome HOME
travail sur monPlusieurs
[tools/eficas.git] / Noyau / strfunc.py
1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2013   EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 """
22 Module rassemblant des fonctions utilitaires de manipulations
23 de chaines de caractères
24 """
25 # module identique à Execution/strfunc.py pour usage dans Eficas
26
27 import locale
28
29 _encoding = None
30 def get_encoding():
31     """Return local encoding
32     """
33     global _encoding
34     if _encoding is None:
35         try:
36             _encoding = locale.getpreferredencoding() or 'ascii'
37         except locale.Error:
38             _encoding = 'ascii'
39     return _encoding
40
41
42 def to_unicode(string):
43     """Try to convert string into a unicode string."""
44     if type(string) is unicode:
45         return string
46     elif type(string) is dict:
47         new = {}
48         for k, v in string.items():
49             new[k] = to_unicode(v)
50         return new
51     elif type(string) is list:
52         return [to_unicode(elt) for elt in string]
53     elif type(string) is tuple:
54         return tuple(to_unicode(list(string)))
55     elif type(string) is not str:
56         return string
57     assert type(string) is str, u"unsupported object: %s" % string
58     for encoding in ('utf-8', 'iso-8859-15', 'cp1252'):
59         try:
60             s = unicode(string, encoding)
61             return s
62         except UnicodeDecodeError:
63             pass
64     return unicode(string, 'utf-8', 'replace')
65
66 def from_unicode(ustring, encoding, errors='replace'):
67     """Try to encode a unicode string using encoding."""
68     try:
69         return ustring.encode(encoding)
70     except UnicodeError:
71         pass
72     return ustring.encode(encoding, errors)
73
74 def convert(content, encoding=None, errors='replace'):
75     """Convert content using encoding or default encoding if None."""
76     if type(content) not in (str, unicode):
77         content = unicode(content)
78     if type(content) == str:
79         content = to_unicode(content)
80     return from_unicode(content, encoding or get_encoding(), errors)
81
82 def ufmt(uformat, *args):
83     """Helper function to format a string by converting all its arguments to unicode"""
84     if type(uformat) is not unicode:
85         uformat = to_unicode(uformat)
86     if len(args) == 1 and type(args[0]) is dict:
87         arguments = to_unicode(args[0])
88     else:
89         nargs = []
90         for arg in args:
91             if type(arg) in (str, unicode, list, tuple, dict):
92                 nargs.append(to_unicode(arg))
93             elif type(arg) not in (int, long, float):
94                 nargs.append(to_unicode(str(arg)))
95             else:
96                 nargs.append(arg)
97         arguments = tuple(nargs)
98     try:
99         formatted_string = uformat % arguments
100     except UnicodeDecodeError, err:
101         print type(uformat), uformat
102         print type(arguments), arguments
103         raise
104     return formatted_string