Ver código fonte

scipt:utils add python3 support

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@65787 15284696-431f-4ddb-bdfa-cd5b030d7da7
Pietro Zambelli 9 anos atrás
pai
commit
6b8e4cc953
1 arquivos alterados com 32 adições e 26 exclusões
  1. 32 26
      lib/python/script/utils.py

+ 32 - 26
lib/python/script/utils.py

@@ -149,6 +149,32 @@ class KeyValue(dict):
         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 @@ def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
     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 @@ def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
 
     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 @@ def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
     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.