From 01a81d2fcbfb732d77527bed5002086f61a5d8da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B0=D0=BC=D0=BE=D1=83=D0=BA=D0=B8=D0=BD=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Wed, 15 Sep 2010 09:57:08 +0400 Subject: [PATCH] Changed runOsCommand() (returns in case of error - False, if successful - list) --- pym/cl_datavars.py | 6 ++-- pym/cl_fill.py | 51 +++++++++++++++++---------- pym/cl_utils.py | 32 ++++++----------- pym/server/utils.py | 30 ++++++++-------- pym/update_config/cl_update_config.py | 2 +- 5 files changed, 61 insertions(+), 60 deletions(-) diff --git a/pym/cl_datavars.py b/pym/cl_datavars.py index ad617c7..2b971ab 100644 --- a/pym/cl_datavars.py +++ b/pym/cl_datavars.py @@ -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 diff --git a/pym/cl_fill.py b/pym/cl_fill.py index 76c6d11..b36501f 100644 --- a/pym/cl_fill.py +++ b/pym/cl_fill.py @@ -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() diff --git a/pym/cl_utils.py b/pym/cl_utils.py index d8964ae..214433d 100644 --- a/pym/cl_utils.py +++ b/pym/cl_utils.py @@ -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): '''Вернуть случайный набор символов указанной длины diff --git a/pym/server/utils.py b/pym/server/utils.py index 9a3d597..e671e1f 100644 --- a/pym/server/utils.py +++ b/pym/server/utils.py @@ -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)): """Генератор задержек""" diff --git a/pym/update_config/cl_update_config.py b/pym/update_config/cl_update_config.py index 853498b..c648e05 100644 --- a/pym/update_config/cl_update_config.py +++ b/pym/update_config/cl_update_config.py @@ -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,