command.py 8.1 KB
Newer Older
A
air9 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#!/usr/bin/env python
# coding: utf-8

# Copyright (c) 2020 Huawei Technologies Co., Ltd.
# oec-hardware is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Create: 2020-04-01

import sys
import re
import subprocess


class Command:

    def __init__(self, command):
        """ Creates a Command object that wraps the shell command """
        self.command = command
        self.origin_output = None
        self.output = None
        self.errors = None
        self.returncode = 0
        self.pipe = None
        self.regex = None
        self.single_line = True
        self.regex_group = None

    def _run(self):
        if sys.version_info.major < 3:
            self.pipe = subprocess.Popen(self.command, shell=True,
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE)
        else:
            self.pipe = subprocess.Popen(self.command, shell=True,
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
C
cuixucui 已提交
45
                                         encoding='utf8')
A
air9 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
        (output, errors) = self.pipe.communicate()
        if output:
            #Strip new line character/s if any from the end of output string
            output = output.rstrip('\n')
            self.origin_output = output
            self.output = output.splitlines()
        if errors:
            self.errors = errors.splitlines()
        self.returncode = self.pipe.returncode

    def start(self):
        if sys.version_info.major < 3:
            self.pipe = subprocess.Popen(self.command, shell=True,
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE)
        else:
            self.pipe = subprocess.Popen(self.command, shell=True,
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
C
cuixucui 已提交
67
                                         encoding='utf8')
A
air9 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

    def run(self, ignore_errors=False):
        """ run the command
            ignore_errors: do not raise exceptions
        """
        self._run()
        if not ignore_errors:
            if self.returncode != 0:
                self.print_output()
                self.print_errors()
                raise CertCommandError(self, "returned %d" % self.returncode)

            if self.errors and len(self.errors) > 0:
                self.print_errors()
            #     raise CertCommandError(self, "has output on stderr")

    def run_quiet(self):
        self._run()
        if self.returncode != 0:
            raise CertCommandError(self, "returned %d" % self.returncode)

    def echo(self, ignore_errors=False):
        self.run(ignore_errors)
        self.print_output()
        return

    def print_output(self):
C
cuixucui 已提交
95
        """
C
cuixucui 已提交
96 97
        结果显示
        :return:
C
cuixucui 已提交
98
        """
A
air9 已提交
99 100
        if self.output:
            for line in self.output:
C
cuixucui 已提交
101
                sys.stdout.write(line)
A
air9 已提交
102 103 104 105
                sys.stdout.write("\n")
            sys.stdout.flush()

    def print_errors(self):
C
cuixucui 已提交
106
        """
C
cuixucui 已提交
107 108
        页面显示错误信息
        :return:
C
cuixucui 已提交
109
        """
A
air9 已提交
110 111
        if self.errors:
            for line in self.errors:
C
cuixucui 已提交
112
                sys.stderr.write(line)
A
air9 已提交
113 114 115 116
                sys.stderr.write("\n")
            sys.stderr.flush()

    def pid(self):
C
cuixucui 已提交
117
        """
C
cuixucui 已提交
118 119
        获取管道pid值
        :return:
C
cuixucui 已提交
120
        """
A
air9 已提交
121 122 123 124
        if self.pipe:
            return self.pipe.pid

    def readline(self):
C
cuixucui 已提交
125
        """
C
cuixucui 已提交
126 127
        按行读取输出信息
        :return
C
cuixucui 已提交
128
        """
A
air9 已提交
129 130 131 132
        if self.pipe:
            return self.pipe.stdout.readline()

    def read(self):
C
cuixucui 已提交
133
        """
C
cuixucui 已提交
134 135
        执行命令,并读取结果
        :return:
C
cuixucui 已提交
136
        """
A
air9 已提交
137 138 139 140 141 142 143 144 145 146
        self.pipe = subprocess.Popen(self.command, shell=True,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT)
        if self.pipe:
            return self.pipe.stdout.read().decode('utf-8', 'ignore').rstrip()

    def poll(self):
        if self.pipe:
            return self.pipe.poll()

C
cuixucui 已提交
147
    def _get_str(self, regex=None, regex_group=None, single_line=True, return_list=False):
A
air9 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
        self.regex = regex
        self.single_line = single_line
        self.regex_group = regex_group

        self._run()

        if self.single_line:
            if self.output and len(self.output) > 1:
                raise CertCommandError(self, "Found %u lines of output, expected 1" % len(self.output))

            if self.output:
                line = self.output[0].strip()
                if not self.regex:
                    return line
                # otherwise, try the regex
                pattern = re.compile(self.regex)
                match = pattern.match(line)
                if match:
                    if self.regex_group:
                        return match.group(self.regex_group)
                    # otherwise, no group, return the whole line
                    return line

                # no regex match try a grep-style match
                if not self.regex_group:
                    match = pattern.search(line)
                    if match:
                        return match.group()

            # otherwise
            raise CertCommandError(self, "no match for regular expression %s" % self.regex)

        #otherwise, multi-line or single-line regex
        if not self.regex:
            raise CertCommandError(self, "no regular expression set for multi-line command")
        pattern = re.compile(self.regex)
        result = None
        if return_list:
            result = list()
        if self.output:
            for line in self.output:
                if self.regex_group:
                    match = pattern.match(line)
                    if match:
                        if self.regex_group:
                            if return_list:
                                result.append(match.group(self.regex_group))
                            else:
                                return match.group(self.regex_group)
                else:
                    # otherwise, return the matching line
                    match = pattern.search(line)
                    if match:
                        if return_list:
                            result.append(match.group())
                        else:
                            return match.group()
            if result:
                return result

        raise CertCommandError(self, "no match for regular expression %s" % self.regex)

    def get_str(self, regex=None, regex_group=None, single_line=True, return_list=False, ignore_errors=False):
        result = self._get_str(regex, regex_group, single_line, return_list)
        if not ignore_errors:
            if self.returncode != 0:
                self.print_output()
                self.print_errors()
                raise CertCommandError(self, "returned %d" % self.returncode)

            # if self.errors and len(self.errors) > 0:
            #     raise CertCommandError(self, "has output on stderr")

        return result


class CertCommandError(Exception):
    def __init__(self, command, message):
C
cuixucui 已提交
226
        super(CertCommandError, self).__init__()
A
air9 已提交
227 228
        self.message = message
        self.command = command
C
cuixucui 已提交
229
        self.__message = None
A
air9 已提交
230 231 232 233 234 235 236 237

    def __str__(self):
        return "\"%s\" %s" % (self.command.command, self.message)

    def _get_message(self): return self.__message
    def _set_message(self, value): self.__message = value
    message = property(_get_message, _set_message)