Merge branch 'master' of git.calculate.ru:/calculate-lib

develop
Самоукин Алексей 14 years ago
commit e306933361

@ -23,6 +23,7 @@ import subprocess
import stat
from shutil import copytree, rmtree
import ctypes
import cl_overriding
class _error:
# Здесь ошибки, если они есть
@ -200,50 +201,128 @@ def getpathenv():
lpath=npath+lpath
return ":".join(lpath)
def list2str(list):
'''Функция переводит список в строку'''
return '['+','.join(list)+']'
class MultiReplace:
"""MultiReplace function object
Usage:
replacer = MultiReplace({'str':'efg','in':'asd'})
s = replacer("string")
"""
def __init__(self, repl_dict):
# string to string mapping; use a regular expression
keys = repl_dict.keys()
keys.sort(reverse=True) # lexical order
pattern = u"|".join([re.escape(key) for key in keys])
self.pattern = re.compile(pattern)
self.dict = repl_dict
def replace(self, s):
# apply replacement dictionary to string
def repl(match, get=self.dict.get):
item = match.group(0)
return get(item, item)
return self.pattern.sub(repl, s)
__call__ = replace
def str2dict(s):
"""Convert string to dictionary:
String format:
{'key1':'value1','key2':'val\'ue2'}
"""
value = r'(?:\\\\|\\\'|[^\'])'
pair = r"""
\s*' # begin key
(%(v)s*)
' # end key
\s*:\s* # delimeter key/value
' # begin value
(%(v)s*)
'\s* # end value
""" % {"v":value}
reDict = re.compile(pair, re.X)
reMatchDict = re.compile("""
^{ # begin dict
((%(v)s,)* # many pair with comma at end
%(v)s)? # pair without comma
}$ # end dict
""" % {'v':pair}, re.X)
if reMatchDict.match(s.strip()):
d = dict(reDict.findall(s))
replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''})
for i in d.keys():
d[i] = replaceSlash(d[i])
return d
else:
print _("wrong dict value: %s"%s)
cl_overriding.exit(1)
def str2list(s):
'''Функция переводит строку в список'''
return s[1:-1].split(',')
"""Convert string to list:
def dict2str(dict):
'''Функция перводит словарь в строку'''
return '{'+','.join(["%s:%s" % (str(k),str(v)) \
for (k,v) in dict.items()])+'}' #:
String format:
['value1','val\'ue2']
"""
value = r'(?:\\\\|\\\'|[^\'])'
element = r"""
\s*' # begin value
(%(v)s*)
'\s* # end value
""" % {"v":value}
reList = re.compile(element, re.X)
reMatchList = re.compile("""
^\[ # begin dict
((%(v)s,)* # many elements with comma at end
%(v)s)? # element without comma
\]$ # end dict
""" % {'v':element}, re.X)
if reMatchList.match(s.strip()):
replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''})
return [replaceSlash(i) for i in reList.findall(s)]
else:
print _("wrong list value: %s"%s)
cl_overriding.exit(1)
def str2dict(s):
'''Функция переводит строку в словарь'''
dict = {}
for i in s[1:-1].split(','):
k,v = i.split(':')
dict[k] = v
return dict
def list2str(list):
"""Convert list to string
Return string with escaped \ and '.
"""
replaceSlash = MultiReplace({'\\':'\\\\','\'':'\\\''})
return "[%s]" % ','.join(["'%s'"%replaceSlash(str(i))
for i in list ])
def dict2str(dict):
"""Convert dictionry to string
Return string with escaped \ and '.
"""
replaceSlash = MultiReplace({'\\':'\\\\','\'':'\\\''})
return '{%s}' % ','.join(["'%s':'%s'" % (str(k),replaceSlash(str(v))) \
for (k,v) in dict.items()])
def convertStrListDict(val):
'''Функция определеяется что на входе (строка, список, словарь)
и переводит их в строку и обратно'''
# если подан список
"""Convert data between string, list, dict"""
# if val is list
if type(val) == types.ListType:
return list2str(val)
# если подан словарь
# if val is dictionary
elif type(val) == types.DictType:
return dict2str(val)
# если подана строка
# else it is string
else:
# если поданная строка содержит словарь
if ':' in val and '{' in val:
# detect dictionary
if re.match("^{.*}$",val):
return str2dict(val)
# если поданная строка содержит список
elif ',' in val and '[' in val:
# detect list
elif re.match("^[.*]$",val):
return str2list(val)
# если это просто строка
# else is simple string
else:
return val
def _toUNICODE(val):
"""перевод текста в юникод"""
"""Convert text to unicode"""
if type(val) == types.UnicodeType:
return val
else:
@ -310,4 +389,4 @@ def copyDir(srcDir, destDir):
def removeDir(rmDir):
"""Рекурсивное удаление директории"""
rmtree(rmDir)
return True
return True

Loading…
Cancel
Save