`
IvanLi
  • 浏览: 604084 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

execute a command with timeout in python

阅读更多
class Command(threading.Thread):
    def __init__(self, command, cwd=None, writeConsole=True, timeout=60):
        threading.Thread.__init__(self)
        self.command = command
        self.cwd = cwd
        self.writeConsole = writeConsole
        self.timeout = timeout


    def run(self):
        if self.cwd is not None:
            print '[' + ' '.join(self.command) + '] in ' + self.cwd
        else:
            print '[' + ' '.join(self.command) + ']'
        self.p = subprocess.Popen(self.command, stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE, cwd=self.cwd)

        self.stdout_lines = []
        for stdout_line in iter(self.p.stdout.readline, b''):
            if self.writeConsole:
                sys.stdout.write(stdout_line)
            self.stdout_lines.append(stdout_line)

        self.stderr_lines = []
        for stderr_line in iter(self.p.stderr.readline, b''):
            if self.writeConsole:
                sys.stderr.write(stderr_line)
            self.stderr_lines.append(stderr_line)

        self.result = self.p.poll()


    def exec_command(self):
        self.start()
        self.join(self.timeout)

        if self.is_alive():
            print 'executing [' + ' '.join(self.command) + '] timeout with timeout in seconds =>', self.timeout
            self.p.terminate()      #use self.p.kill() if process needs a kill -9
            self.join()
            sys.exit(1)
        return (self.result, self.stdout_lines, self.stderr_lines)


if __name__ == "__main__":
      result, outs, errs = Command(
        ["/bin/sleep", "3"], writeConsole=True, timeout=2).exec_command()
    Command(
        ["/bin/echo", "3"], writeConsole=True, timeout=2).exec_command()
分享到:
评论

相关推荐

    selenium webdriverAPI-python

    - `timeout`: The timeout duration in seconds to wait for the WebDriver server to start (default: 30). - `host`: The host address of the WebDriver server (default: None). - `log_level`: The logging ...

    Advanced Apple Debugging & Reverse Engineering v0.9.5

    It’s time to talk about a new class in the lldb Python module, SBValue, and how it can simplify the parsing of JIT code output. 22. SB Examples, Improved Lookup For the rest of the chapters in this...

    RobotFramework中SSHLibrary学习与总结.pdf

    Open Connection host=10.69.140.112 port=2222 timeout=10 seconds prompt=$ ``` - **Get Connection**:获取已建立的连接信息,可以指定索引或别名,如果不指定,则返回当前连接的信息。 ```robotframework ${con...

    python中执行shell的两种方法总结

    def execute_command(cmdstring, cwd=None, timeout=None, shell=False): """ 执行一个Shell命令。 封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr。 参数: cwd: 运行命令时更改路径...

    vmware unlocker 2.0.6最新版(vm虚拟机破解安装Mac OS)

    There are some challenges to write the code as ESXi has a subset of Python 2.7 which constrains some modules that can be used. 2. Prerequisites The code requires Python 2.7 to work. Most Linux ...

    Python基于模块Paramiko实现SSHv2协议

    - `connect()`:这是建立与远程服务器连接的主要方法,必须提供hostname参数,其他可选参数包括port(默认为SSH标准端口22)、username、password、pkey或key_filename用于身份验证,以及timeout、allow_agent和look...

    wait-for-it:纯bash脚本来测试并等待TCP主机和端口的可用性

    用法wait-for-it.sh host:port [-s] [-t timeout] [-- command args]-h HOST | --host=HOST Host or IP under test-p PORT | --port=PORT TCP port under test Alternatively, you specify the host and port as ...

    unlocker208 —— VMware 安装 MacOS的必备补丁

    There are some challenges to write the code as ESXi has a subset of Python 2.7 which constrains some modules that can be used. 2. Prerequisites ---------------- The code requires Python 2.7 to work....

    pytest+Appium_allure

    'timeout': 5000 }) return result['stdout'] ``` 四、使用 Appium 截取元素图片 Appium 提供了一个截取元素图片的方法,可以使用以下代码实现: ``` element = self.driver.find_element_by_id('...

Global site tag (gtag.js) - Google Analytics