Merge "Change PTL informatin in INFO"
[bottlenecks.git] / testsuites / vstf / vstf_scripts / vstf / agent / env / basic / commandline.py
1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import subprocess
11 import threading
12 import logging
13 from vstf.common import constants
14
15 LOG = logging.getLogger(__name__)
16
17
18 class CommandLine(object):
19
20     def __init__(self):
21         super(CommandLine, self).__init__()
22         self.proc = None
23         self.is_timeout = False
24
25     def __kill_proc(self):
26         self.is_timeout = True
27         self.proc.kill()
28
29     def execute(self, cmd, timeout=constants.TIMEOUT, shell=False):
30         """this func call subprocess.Popen(),
31         here setup a timer to deal with timeout.
32         :param cmd: cmd list like ['ls', 'home']
33         :param timeout: for timer count for timeout
34         :return: (ret, output) the output (stdout+'\n'+stderr)
35         """
36         # reset the timeout flag
37         self.is_timeout = False
38         self.proc = subprocess.Popen(cmd,
39                                      stdout=subprocess.PIPE,
40                                      stderr=subprocess.PIPE,
41                                      shell=shell)
42
43         timer = threading.Timer(timeout, self.__kill_proc, [])
44         timer.start()
45         stdout, stderr = self.proc.communicate()
46         timer.cancel()
47
48         if self.proc.returncode or self.is_timeout:
49             if self.is_timeout:
50                 LOG.error("run cmd<%(cmd)s> timeout", {"cmd": cmd})
51             ret = False
52             output = "".join([stderr, stdout])
53         else:
54             ret = True
55             output = stdout
56         return ret, output