调用subprocess 使用logging打印日志

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Henry  17607168727@163.com

import sys
import logging
from logging.handlers import TimedRotatingFileHandler
import os
from subprocess import Popen, PIPE, STDOUT
reload(sys)
sys.setdefaultencoding('utf8')


LOG_FILE_NAME = 'send_snmp_trap.log'
logger = logging.getLogger('SenSNMPTrap.py')
logger.setLevel(level=logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(process)d - %(levelname)s - %(message)s')
LOG_PATH = os.path.join('/tmp', LOG_FILE_NAME)

# 每天午夜更新日志文件
handler = TimedRotatingFileHandler(LOG_PATH, when='midnight', backupCount=3, )
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)
logger.addHandler(handler)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
# 输出到屏幕
logger.addHandler(console)


def log_subprocess_output(pipe):
    for line in iter(pipe.readline, b''):  # b'\n'-separated lines
        logger.info('got line from subprocess: %r', line)


def run_command(command_line_args):
    process = Popen(command_line_args, stdout=PIPE, stderr=STDOUT)
    with process.stdout:
        log_subprocess_output(process.stdout)
    exitcode = process.wait()  # 0 means success
    if exitcode == 0:
        logger.info('success')
    else:
        logger.error("failed")


run_command(command_line_args=['ls', '/tp/'])
posted @ 2019-07-25 17:44  random_lee  阅读(1467)  评论(0编辑  收藏  举报