Python常用代码笔记

参数解析

import sys
import getopt

try:
    opts,args = getopt.getopt(sys.argv[1:], "ho:",["help", "output="]);
    if not opts:
        usage()
    for opt,arg in opts:
        if opt in ("-h", "--help"):
            usage();
        elif opt in ("-H",):
            mysql_host = arg
        elif opt in ("-o",):
            parse_cpu_csv(arg)
        else:
            usage()
            sys.exit(1)
except getopt.GetoptError:
    usage();
    sys.exit(1)

时间转换

import time
import datetime
 

获取当前主机unix time

time.mktime(datetime.datetime.now().timetuple())

unix time转datetime

datetime.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S')

datetime转unix time

time.mktime(datetime.datetime.strptime(time,"%Y-%m-%d %H:%M:%S").timetuple())

日志模块

import logging

def init_logger():
    logger = logging.getLogger('mylogger') 
    logger.setLevel(logging.INFO) 
       
    fh = logging.FileHandler('disk_detect.log') 
    fh.setLevel(logging.INFO) 
     
    ch = logging.StreamHandler(sys.stdout) 
    ch.setLevel(logging.INFO) 
       
    formatter = logging.Formatter('%(levelname)s [%(asctime)s] [message="%(message)s"]') 
    fh.setFormatter(formatter) 
    ch.setFormatter(formatter) 
       
    logger.addHandler(fh) 
    logger.addHandler(ch)
    return logger

执行系统命令

from subprocess import Popen, PIPE

def runCmd(cmd):
    child = Popen(cmd, stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = True)
    out, err = child.communicate()
    ret = child.wait()
    return (out, err, ret)
(out,err,ret) = runCmd('bash /tmp/1.sh')

DocString文档

在脚本最开始

'''
Firefoxbug function : for test

Usage main.py <options>

    --version  : print version information
    -h         : print help
    -g         : upload all collected data to gateway, plese use IP address
                 e.g -g 10.249.x.x
    -i         : mark self as gateway, gateway server must be use this option
                 e.g -g 10.249.x.x -i
'''

import sys

def usage(exitarg):
    print __doc__
    sys.exit(exitarg)

标签:Python