Python Code Snippets - WBowam/wbowam.github.com GitHub Wiki

Date: 2015-03-30
Title: Python 代码片段
Tags: Snippets, Python
Category: IT

python logging

import logging  
logging.basicConfig(filename = os.path.join(os.getcwd(), 'log.txt'), level = logging.DEBUG)  
logging.debug('this is a message')  

python get line num

f = open("test.txt")
for i, l in enumerate(f):
    print i

python 脚本基本结构

import sys

source_file = sys.argv[1]

if __name__ == "__main__":
     my_func(source_file)

python file

f = open(file, "a") ## a meaning append
f = open(file, "w") ## w meaning write

python 正则

import re
pattern = re.compile("[a-zA-Z]")
result = pattern.search("adsfuhefdfkj435")
print result.group()

python 下载静态文件,如,mp3

import urllib
urllib.urlretrieve(audio_url, "name.mp3")

升级pip

easy_install -U pip

dir()

  • built-in function;
  • return a list of valid attributes for an object;
  • default: global objects

decode(), encode()

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。

python 中使用redis

import redis

> cache = redis.Redis(‘127.0.0.1’, ‘6379’, 0)  ## 指定本地服务, 6379端口, 第一个数据库
> cache.lpush(“my_key”, 999)  ## 往队列”my_key”里推进新值
> cache.lrange(“my_key”)  ## 取出队列的值
[‘999’, '23', '22', '21', '20', '19', '18', '17', '16', '15', '14', '13', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', ‘1']