Salome HOME
mise en coherence avec la V7.7 d eficas canal historique
[tools/eficas.git] / Noyau / strfunc.py
1 # coding=utf-8
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 """Module rassemblant des fonctions utilitaires de manipulations
21 de chaines de caractères
22 """
23 # module identique à Execution/strfunc.py pour usage dans Eficas
24
25 import locale
26
27 _encoding = None
28
29
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
67 def from_unicode(ustring, encoding, errors='replace'):
68     """Try to encode a unicode string using encoding."""
69     try:
70         return ustring.encode(encoding)
71     except UnicodeError:
72         pass
73     return ustring.encode(encoding, errors)
74
75
76 def convert(content, encoding=None, errors='replace'):
77     """Convert content using encoding or default encoding if None."""
78     if type(content) not in (str, unicode):
79         content = unicode(content)
80     if type(content) == str:
81         content = to_unicode(content)
82     return from_unicode(content, encoding or get_encoding(), errors)
83
84
85 def ufmt(uformat, *args):
86     """Helper function to format a string by converting all its arguments to unicode"""
87     if type(uformat) is not unicode:
88         uformat = to_unicode(uformat)
89     if len(args) == 1 and type(args[0]) is dict:
90         arguments = to_unicode(args[0])
91     else:
92         nargs = []
93         for arg in args:
94             if type(arg) in (str, unicode, list, tuple, dict):
95                 nargs.append(to_unicode(arg))
96             elif type(arg) not in (int, long, float):
97                 nargs.append(to_unicode(str(arg)))
98             else:
99                 nargs.append(arg)
100         arguments = tuple(nargs)
101     formatted_string=""
102     try:
103         formatted_string = uformat % arguments
104     except UnicodeDecodeError, err:
105         print type(uformat), uformat
106         print type(arguments), arguments
107         raise
108     return formatted_string