Python简单技巧和常用参考

     2017年11月09日       江南兔子哥       非专业笔记->Python       python 

python文件支持中文

# -*- coding: UTF-8 -*-

另类字典访问方法

class AttributeDict(dict):
    def __getattr__(self, attr):
        try:
            return self[attr]
        except:
            return None

    def __setattr__(self, attr, value):
        self[attr] = value

ad = AttributeDict({"aa":1})
print ad.aa

执行shell命令

from subprocess import Popen, PIPE
def run_cmd(cmd):
    #Popen call wrapper.return (code, stdout, stderr)
    child = Popen(cmd, stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = True)
    out, err = child.communicate()
    ret = child.wait()
    return (ret, out, err)

获取当前python脚本文件所在路径

import os
os.path.split(os.path.realpath(__file__))[0]

json模块 import的问题

try :
    import json
except :
    import simplejson as json

使用json工具格式化json

#python 2.7以下
echo '{"hello":1}' | python -m simplejson.tool
#python 2.7及以上
echo '{"hello":1}' | python -m json.tool

获取URL资源

import urllib2
response = urllib2.urlopen('http://www.opstool.com/')
html = response.read()
print html

关于main

if __name__=='__main__':

指定格式的日期

import datetime
yesterday =datetime.date.today() -datetime.timedelta(days=1)
pt = yesterday.strftime("%Y%m%d")
print pt

timestamp转化为日期时间

timeStamp = 1437122504
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)

使用date parser 从字符串产生datetime变量

import time
from dateutil import parser

dt = parser.parse("2017-11-09 03:23:56.345024 +0800")

time.mktime(dt.timetuple()) + dt.microsecond

日期时间字符串 转化为timestamp

int(time.mktime( time.strptime("2015-07-21 10:23:00", "%Y-%m-%d %H:%M:%S")))

获得当前时间

import datetime
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

使用option

import getopt
try:
    opts, args = getopt.getopt(sys.argv[1:], "t:")
    for op, value in opts:
        if op == '-t':
            gctime =  int(value)
except getopt.GetoptError:
    sys.exit(1)

使用logger

import os
import logging

def get_logger(logger_name):
    # 创建一个logger
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)

    # 创建一个handler,用于写入日志文件
    fh = logging.FileHandler(os.path.split(os.path.realpath(__file__))[0]+"/"+logger_name+".log")
    fh.setLevel(logging.DEBUG)

    # 再创建一个handler,用于输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # 定义handler的输出格式
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # 给logger添加handler
    logger.addHandler(fh)
    logger.addHandler(ch)
    return logger

logger=get_logger("mylogger")

实现deamon运行

import sys
import os

def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
    # Perform first fork.
    try:
        pid = os.fork( )
        if pid > 0:
            sys.exit(0) # Exit first parent.
    except OSError, e:
        sys.stderr.write("fork #1 failed: (%d) %sn" % (e.errno, e.strerror))
        sys.exit(1)
    # Decouple from parent environment.
    os.chdir("/")
    os.umask(0)
    os.setsid( )
    # Perform second fork.
    try:
        pid = os.fork( )
        if pid > 0:
            sys.exit(0) # Exit second parent.
    except OSError, e:
        sys.stderr.write("fork #2 failed: (%d) %sn" % (e.errno, e.strerror))
        sys.exit(1)
    # The process is now daemonized, redirect standard file descriptors.
    for f in sys.stdout, sys.stderr: f.flush( )
    si = file(stdin, 'r')
    so = file(stdout, 'a+')
    se = file(stderr, 'a+', 0)
    os.dup2(si.fileno( ), sys.stdin.fileno( ))
    os.dup2(so.fileno( ), sys.stdout.fileno( ))
    os.dup2(se.fileno( ), sys.stderr.fileno( ))

#进入后台
daemonize()

简单HTTP服务器示例

import urllib
from cgi import parse_header, parse_multipart
from urlparse import parse_qs

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class TestHTTPHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        buf="Hello World!"
        self.protocal_version = "HTTP/1.1"
        self.send_response(200)
        self.end_headers()
        self.wfile.write(buf)

    def do_POST(self):
        self.protocal_version = "HTTP/1.1"
        self.send_response(200)
        self.end_headers()
        buf = self._parse_POST()
        self.wfile.write(buf['postvar'])

    def _parse_POST(self):
        ctype, pdict = parse_header(self.headers['content-type'])
        if ctype == 'multipart/form-data':
            postvars = parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers['content-length'])
            postvars = parse_qs(
                    self.rfile.read(length),
                    keep_blank_values=1)
        else:
            postvars = {}
        return postvars
def start_server():
    http_server = HTTPServer(("127.0.0.1", 8088), TestHTTPHandler)
    http_server.serve_forever()

start_server()

一种函数调用方法

#!/bin/env python

def mytest():
    print "hello"

m={
    'myfunction' : 'mytest'
}

globals()[m['myfunction']]()

print globals()

logging的日志级别大小关系

日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET