Changed runOsCommand() (returns in case of error - False, if successful - list)

develop
Самоукин Алексей 14 years ago
parent 9731b2e6e1
commit 01a81d2fcb

@ -753,14 +753,12 @@ storage of variables templates")%location)
class glob_attr:
"""Глобальные аттрибуты для методов заполнения переменных"""
def _runos(self,cmd, ret_first=None, env={},ret_list=False):
def _runos(self, cmd, env={}):
"""Вернуть результат выполнения команды ОС"""
if not env:
envDict = {}
env.update(os.environ.items() + [("PATH",getpathenv())] +\
env.items())
retCode, programOut = runOsCommand(cmd, None, ret_first, env,
ret_list)
retCode, programOut = runOsCommand(cmd, None, env_dict=env)
if not retCode:
return programOut
return False

@ -270,7 +270,13 @@ class fillVars(glob_attr):
def get_os_net_domain(self):
'''Определим домен'''
domain=self._runos("hostname -d 2>&1")
textLines = self._runos("hostname -d 2>&1")
if textLines is False:
cl_overriding.printERROR(_("Error execute 'hostname -d'"))
cl_overriding.exit(1)
domain = ""
if textLines:
domain = textLines[0]
if not domain:
cl_overriding.printERROR(_("Error:") + " " +\
_("Not found domain name"))
@ -382,7 +388,10 @@ class fillVars(glob_attr):
def get_from_uname():
"""Get version from uname"""
kernelVersion=self._runos("uname -r")
textLines = self._runos("uname -r")
kernelVersion = ""
if textLines:
kernelVersion = textLines[0]
if kernelVersion:
return kernelVersion.partition("-")[0]
return get_from_metapackage() or get_from_calculate_ini() or \
@ -390,18 +399,22 @@ class fillVars(glob_attr):
def get_os_net_hostname(self):
'''Считать имя компьютера net_host'''
hostname=self._runos("hostname -s 2>&1")
if not hostname:
return ""
if re.search("^hostname: ",hostname):
hostname=self._runos("hostname 2>&1")
textLines = self._runos("hostname -s 2>&1")
hostname = ""
if textLines:
hostname = textLines[0]
if not hostname:
return ""
if re.search("^hostname: ",hostname):
return self.Get('os_linux_shortname')
else:
if hostname=='livecd':
if re.search("^hostname: ",hostname):
textLines = self._runos("hostname 2>&1")
if not textLines:
return ""
hostname = textLines[0]
if re.search("^hostname: ",hostname):
return self.Get('os_linux_shortname')
else:
if hostname=='livecd':
return self.Get('os_linux_shortname')
return hostname
# все ip
@ -465,9 +478,10 @@ class fillVars(glob_attr):
def get_os_arch_machine(self):
"""архитектура процессора"""
march = self._runos("uname -m")
if not march:
textLines = self._runos("uname -m")
if not textLines:
return ""
march = textLines[0]
return march
def get_os_root_dev(self):
@ -846,15 +860,16 @@ class fillVars(glob_attr):
def get_hr_laptop(self):
"""Если компьютер ноутбук, то его производитель"""
formfactor = self._runos("hal-get-property --udi \
textLines = self._runos("hal-get-property --udi \
/org/freedesktop/Hal/devices/computer --key system.formfactor")
if not formfactor:
if not textLines:
return ""
formfactor = textLines[0]
if formfactor == 'laptop':
vendor = self._runos("hal-get-property --udi \
textLines = self._runos("hal-get-property --udi \
/org/freedesktop/Hal/devices/computer --key system.hardware.vendor")
if vendor:
vendor = vendor.split(" ")[0]
if textLines:
vendor = textLines[0].split(" ")[0]
else:
vendor = "unknown"
return vendor.lower()

@ -248,17 +248,14 @@ class process:
"""Failed or not"""
return self.returncode() != 0
def runOsCommand(cmd,inStr=None,ret_first=None,env_dict=None,ret_list=False):
def runOsCommand(cmd,in_str=None, env_dict=None):
"""Выполняет внешнюю программу
Параметры:
cmd внешняя программа
inStr данные передаваемые программе на страндартный вход.
ret_first вернуть только первую строку
in_str данные передаваемые программе на страндартный вход.
env_dict словарь переменных окружения
Возвращаемые параметры:
строка/строки которую выведет внешняя программа
Возвращает код возврата, stdout+stderr
Возвращает (код возврата, список stdout+stderr)
"""
pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
@ -268,25 +265,16 @@ def runOsCommand(cmd,inStr=None,ret_first=None,env_dict=None,ret_list=False):
shell=True)
fout, fin, ferr = (pipe.stdout, pipe.stdin, pipe.stderr)
# если есть данные на вход, передать их
if inStr:
fin.write(inStr)
if in_str:
fin.write(in_str)
fin.close()
# Код возврата
retcode = pipe.wait()
res = fout.readlines()
res = fout.read().split("\n")
fout.close()
res += ferr.readlines()
res += ferr.read().split("\n")
ferr.close()
if res:
if ret_list:
if ret_first:
return retcode, res[:1]
return retcode, res
elif len(res) == 1 or ret_first:
return retcode, res[0].strip()
else:
return retcode, res
return retcode, None
# Код возврата
retcode = pipe.wait()
return retcode, res
def genpassword(passlen=9):
'''Вернуть случайный набор символов указанной длины

@ -108,22 +108,22 @@ def rawInput(promptText="", inputText=""):
readline.set_pre_input_hook(None)
return strInput
def execProg(cmdStrProg, inStr=False, retFull=True, envProg={}):
"""Выполняет внешнюю программу
def execProg(self, cmdStrProg, inStr=False, envProg={}):
"""Выполняет внешнюю программу
Параметры:
cmdStrProg внешняя программа
inStr данные передаваемые программе на страндартный вход.
Возвращаемые параметры:
строка которую выведет внешняя программа или False в случае ошибки
"""
env_path = {"PATH":getpathenv()}
env = {}
env.update(os.environ.items() + env_path.items() + envProg.items())
retCode,programOut = runOsCommand(cmdStrProg,inStr,retFull,env)
if not retCode:
return programOut
return False
Параметры:
cmdStrProg внешняя программа
inStr данные передаваемые программе на страндартный вход.
Возвращаемые параметры:
строки которые выведет внешняя программа или False в случае ошибки
"""
env_path = {"PATH":getpathenv()}
env = {}
env.update(os.environ.items() + env_path.items() + envProg.items())
retCode,programOut = runOsCommand(cmdStrProg,in_str=inStr,env_dict=env)
if not retCode:
return programOut
return False
def genSleep(timeSleep=(0.2, 0.4, 0.8)):
"""Генератор задержек"""

@ -131,7 +131,7 @@ class updateUserConfigs(shareUpdateConfigs):
retCode, resWho = runOsCommand("who")
xUsers = []
if retCode==0:
if resWho and type(resWho) == list:
if resWho:
xUsers = map(lambda x: x[0],
filter(lambda x: x[1].startswith(":"),
map(lambda x: filter(lambda y: y,

Loading…
Cancel
Save