前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python调用系统命令设置超时时间

Python调用系统命令设置超时时间

作者头像
py3study
发布2020-01-09 14:35:09
2.9K0
发布2020-01-09 14:35:09
举报
文章被收录于专栏:python3python3

    python通过subprocess模块调用系统命令。实际使用中,有一次是命令进入了交互模式,结果web端直接卡死了。调用时设置一个超时时间,时间用完后自动断开。这样就避免了系统因为调用命令而僵死的问题。

代码语言:javascript
复制
def sys_command_outstatuserr(cmd, timeout=120):
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
    t_beginning = time.time()
    seconds_passed = 0
    while True:
        if p.poll() is not None:
            res = p.communicate()
            exitcode = p.poll() if p.poll() else 0
            return res[0], exitcode, res[1]
        seconds_passed = time.time() - t_beginning
        if timeout and seconds_passed > timeout:
            p.terminate()
            out, exitcode, err = '', 128, '执行系统命令超时'
            return out, exitcode, err
        time.sleep(0.1)

def sys_command_outstatuserr(cmd, timeout=120):

    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)

    t_beginning = time.time()

    seconds_passed = 0

    while True:

        if p.poll() is not None:

            res = p.communicate()

            exitcode = p.poll() if p.poll() else 0

            return res[0], exitcode, res[1]

        seconds_passed = time.time() - t_beginning

        if timeout and seconds_passed > timeout:

            p.terminate()

            out, exitcode, err = '', 128, '执行系统命令超时'

            return out, exitcode, err

        time.sleep(0.1)

def sys_command_outstatuserr(cmd, timeout=120):

    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)

    t_beginning = time.time()

    seconds_passed = 0

    while True:

        if p.poll() is not None:

            res = p.communicate()

            exitcode = p.poll() if p.poll() else 0

            return res[0], exitcode, res[1]

        seconds_passed = time.time() - t_beginning

        if timeout and seconds_passed > timeout:

            p.terminate()

            out, exitcode, err = '', 128, '执行系统命令超时'

            return out, exitcode, err

        time.sleep(0.1)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
命令行工具
腾讯云命令行工具 TCCLI 是管理腾讯云资源的统一工具。使用腾讯云命令行工具,您可以快速调用腾讯云 API 来管理您的腾讯云资源。此外,您还可以基于腾讯云的命令行工具来做自动化和脚本处理,以更多样的方式进行组合和重用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档