[GRASS-SVN] r65787 - grass/trunk/lib/python/script

svn_grass at osgeo.org svn_grass at osgeo.org
Wed Jul 29 07:05:37 PDT 2015


Author: zarch
Date: 2015-07-29 07:05:37 -0700 (Wed, 29 Jul 2015)
New Revision: 65787

Modified:
   grass/trunk/lib/python/script/utils.py
Log:
scipt:utils add python3 support

Modified: grass/trunk/lib/python/script/utils.py
===================================================================
--- grass/trunk/lib/python/script/utils.py	2015-07-29 14:04:38 UTC (rev 65786)
+++ grass/trunk/lib/python/script/utils.py	2015-07-29 14:05:37 UTC (rev 65787)
@@ -149,6 +149,32 @@
         self[key] = value
 
 
+def decode(string):
+    """Decode string with defualt locale
+
+    :param str string: the string to decode
+    """
+    enc = locale.getdefaultlocale()[1]
+    if enc:
+        if hasattr(string, 'decode'):
+            return string.decode(enc)
+
+    return string
+
+
+def encode(string):
+    """Encode string with defualt locale
+
+    :param str string: the string to encode
+    """
+    enc = locale.getdefaultlocale()[1]
+    if enc:
+        if hasattr(string, 'encode'):
+            return string.encode(enc)
+
+    return string
+
+
 def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
     """Parse a string into a dictionary, where entries are separated
     by newlines and the key and value are separated by `sep` (default: `=`)
@@ -172,6 +198,10 @@
     if not s:
         return result
 
+    if isinstance(s, bytes):
+        sep = encode(sep)
+        vsep = encode(vsep) if vsep else vsep
+
     if vsep:
         lines = s.split(vsep)
         try:
@@ -183,9 +213,9 @@
 
     for line in lines:
         kv = line.split(sep, 1)
-        k = kv[0].strip()
+        k = decode(kv[0].strip())
         if len(kv) > 1:
-            v = kv[1].strip()
+            v = decode(kv[1].strip())
         else:
             v = dflt
 
@@ -197,30 +227,6 @@
     return result
 
 
-def decode(string):
-    """Decode string with defualt locale
-
-    :param str string: the string to decode
-    """
-    enc = locale.getdefaultlocale()[1]
-    if enc:
-        return string.decode(enc)
-
-    return string
-
-
-def encode(string):
-    """Encode string with defualt locale
-
-    :param str string: the string to encode
-    """
-    enc = locale.getdefaultlocale()[1]
-    if enc:
-        return string.encode(enc)
-
-    return string
-
-
 def get_num_suffix(number, max_number):
     """Returns formatted number with number of padding zeros
     depending on maximum number, used for creating suffix for data series.



More information about the grass-commit mailing list