前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >subprocess实时获取结果和捕获错误

subprocess实时获取结果和捕获错误

作者头像
机器学习和大数据挖掘
发布2019-07-01 18:24:44
6.1K2
发布2019-07-01 18:24:44
举报
文章被收录于专栏:数据挖掘

需要调用命令行来执行某些命令,主要是用 subprocess 实时获取结果和捕获错误,发现subprocess的很多坑。

subprocess 普通获取结果方式,其需要命令完全执行才能返回结果:

代码语言:javascript
复制
import subprocess

scheduler_order = "df -h"
return_info = subprocess.Popen(scheduler_order, shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)

for next_line in return_info.stdout:
    return_line = next_line.decode("utf-8", "ignore")
    print(return_line)

subprocess 实时获取结果:

代码语言:javascript
复制
import subprocess

scheduler_order = "df -h"
return_info = subprocess.Popen(scheduler_order, shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
while True:
    next_line = return_info.stdout.readline()
    return_line = next_line.decode("utf-8", "ignore")
    if return_line == '' and return_info.poll() != None:
        break
    print(return_line)

想要获取报错机制,使用 check_output 捕捉报错和使用 check_call 捕捉报错,及时在 Popen 中捕获报错,都会使 实时输出失效 !,所以自行查看 CalledProcessError 源码终于搞定。

实时发送以及捕获报错:

代码语言:javascript
复制
import subprocess

try:
    scheduler_order = "top -u ybtao"
    return_info = subprocess.Popen(scheduler_order, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while True:
        next_line = return_info.stdout.readline()
        return_line = next_line.decode("utf-8", "ignore")
        if return_line == '' and return_info.poll() != None:
            break
        print(return_line)

    returncode = return_info.wait()
    if returncode:
        raise subprocess.CalledProcessError(returncode, return_info)
except Exception as e:
    print(e)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-11-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档