1. commands模块,比subprocess和os.popen好用
如下执行shell命令,同时获取返回值和结果
>>>commands.getstatusoutput('ls /bin/ls')
>>>(0,'/bin/ls')
2. collections.Counter类
>>> from collections import Counter
>>> fruits = ['orange', 'banana', 'apple', 'orange', 'banana']
>>> Counter(fruits)
Counter({'orange': 2, 'banana': 2, 'apple': 1})
3.copy模块
copy.copy(x): ref copy
copy.deepcopy(x): object copy
4. ConfigParser模块
cat format.conf
[DEFAULT]
conn_str = %(dbn)s://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s
dbn = mysql
user = root
host = localhost
port = 3306
[db1]
user = aaa
pw = ppp
db = example1
[db2]
host = 192.168.0.110
pw = www
db = example
---------------------------------------------------------
cat readformat.py
import ConfigParser
conf = ConfigParser.ConfigParser()
conf.read('format.conf')
print conf.get('db1', 'conn_str')
print conf.get('db2', 'conn_str')
-----------------------------------------------------------
python readformat.py
mysql://aaa:ppp@localhost:3306/example1
mysql://root:[email protected]:3306/example
5.argparse代替optparse
1)argparse支持参数分组
2)argparse支持子命令
3)支持 非法参数处理
指定type和default参数
cat prog.py
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",type=int,default=3)
args=parser.parse_args()
print args.square**2
下面是运行结果:
$python prog.py 4
16
6. pandas处理csv
7.小于1G的xml用xml.etree.ElementTree, 大于1G的用lxml
ref some examples of beautiful Pythonic code