You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
calculate-utils-2.2-lib/pym/cl_utils.py

156 lines
5.3 KiB

#-*- coding: utf-8 -*-
# Copyright 2008-2010 Mir Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import string
from random import choice
import os
import types
import subprocess
class _error:
# Здесь ошибки, если они есть
error = []
def getError(self):
"""Выдать ошибки"""
if not self.error:
return False
error = ""
for e in self.error:
error += e + "\n"
return error
def setError(self, error):
"""Установка ошибки"""
self.error.append(error)
return True
def runOsCommand(cmd, inStr=None, ret_first=None, env_dict=None):
"""Выполняет внешнюю программу
Параметры:
cmd внешняя программа
inStr данные передаваемые программе на страндартный вход.
ret_first вернуть только первую строку
env_dict словарь переменных окружения
Возвращаемые параметры:
строка/строки которую выведет внешняя программа
Возвращает код возврата, stdout+stderr
"""
pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env_dict,
close_fds=True,
shell=True)
fout, fin, ferr = (pipe.stdout, pipe.stdin, pipe.stderr)
# если есть данные на вход, передать их
if inStr:
fin.write(inStr)
fin.close()
# Код возврата
retcode = pipe.wait()
res = fout.readlines()
fout.close()
res += ferr.readlines()
ferr.close()
if res:
if len(res) == 1 or ret_first:
return retcode, res[0].strip()
else:
return retcode, res
return retcode, None
def genpassword(passlen=9):
'''Вернуть случайный пассворд указанной длины
Параметры:
passlen длина пароля который нужно сгенерировать
Возвращаемые параметры:
Сгенерированный пароль указанной длины
'''
res=''.join([choice(string.ascii_letters+string.digits)\
for i in xrange(passlen)])
return res
def fillstr(char, width):
'''Заполнить строку указанным числом символов. Псеводоним символ*кол-во'''
return str(char) * width
def getpathenv():
"""Вернуть пути для запуска утилит"""
bindir=['/sbin','/bin','/usr/sbin','/usr/bin']
env=os.environ
if env and env.has_key('PATH'):
lpath=env['PATH'].split(":")
npath=[]
for dirname in bindir:
if os.path.exists(dirname) and dirname not in lpath:
npath.append(dirname)
lpath=npath+lpath
return ":".join(lpath)
def list2str(list):
'''Функция переводит список в строку'''
return '['+','.join(list)+']'
def str2list(s):
'''Функция переводит строку в список'''
return s[1:-1].split(',')
def dict2str(dict):
'''Функция перводит словарь в строку'''
return '{'+','.join(["%s:%s" % (str(k),str(v)) \
for (k,v) in dict.items()])+'}' #:
def str2dict(s):
'''Функция переводит строку в словарь'''
dict = {}
for i in s[1:-1].split(','):
k,v = i.split(':')
dict[k] = v
return dict
def convertStrListDict(val):
'''Функция определеяется что на входе (строка, список, словарь)
и переводит их в строку и обратно'''
# если подан список
if type(val) == types.ListType:
return list2str(val)
# если подан словарь
elif type(val) == types.DictType:
return dict2str(val)
# если подана строка
else:
# если поданная строка содержит словарь
if ':' in val and '{' in val:
return str2dict(val)
# если поданная строка содержит список
elif ',' in val and '[' in val:
return str2list(val)
# если это просто строка
else:
return val
def _toUNICODE(val):
"""перевод текста в юникод"""
if type(val) == types.UnicodeType:
return val
else:
return str(val).decode('UTF-8')