subprocess實時獲取結果和捕獲錯誤

須要調用命令行來執行某些命令,主要是用 subprocess 實時獲取結果和捕獲錯誤,發現subprocess的不少坑。python

subprocess 普通獲取結果方式,其須要命令徹底執行才能返回結果:shell

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 實時獲取結果:命令行

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 源碼終於搞定。code

實時發送以及捕獲報錯:utf-8

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)
相關文章
相關標籤/搜索