Sunday, September 28, 2008

[Python] 一些小tips

(1) 用isinstance判断变量类型
>>>A = [1,2,3,4]
>>>isinstance(A, list)


(2) sort, reverse 以及 sorted, reversed
A=[3,1,2]
assert(A.sort() == sorted(A))
assert(A.reverse() == reversed(A))


(3) 一个简单的命令行progress bar:
def progress_bar(current, total, width=20):
i = int (current*width/total)
sys.stdout.write("\r|" + '*'*i + ' '*(width-i)+"|")


(4) PyYaml最简单的用法
  • 把一个变量A dump到一个文件f中
    A = {1:'a', 2:'b'}
    yaml.dump(A, f)

  • 从外部yaml文件文件load出数据到A
    A=yaml.load(filehandler)
    


(5) 读取命令行的输入:
  • input(prompt)
  • raw_input(prompt)
  • import getpass
    getpass.getpass(prompt)

(6) 使用re正则表达式
import re
>>>m = re.match(r"(\d+)\s*(M|K)(bit|Byte)", "1024Mbit")
>>>print m.group(1), m.group(2)+m.group(3)
1024 Mbit

还可以使用(?P)来acess匹配到的字符串
m = re.match(r"(?P\d+)\s*(M|K)(bit|Byte)", "1024Mbit")
>>>print m.group("num"), m.group(2)+m.group(3)
1024 Mbit

为了提高使用正则表达式的效率, 可以先编译正则表达式, 然后每次用编译出来的正则字符串去匹配
>>>p = re.compile(r"(\d+)\s*(M|K)(bit|Byte)")
>>>g = p.match("1024Mbit")
>>>print g.group(1), g.group(2)+g.group(3)
1024 Mbit


(7)显示异常的类型和错误信息
try:
    do what you want
    except:
        print sys.exc_info()[0], sys.exc_info()[1]
sys.exc_info()[0]: 异常的类型
sys.exc_info()[1]: 异常的信息

(8) Python 2.5以后支持with 语句. 用在file object上,就不用close这个文件了
with open("max_load_vs_k.dat","w") as f:
    do some file operation with f


(9)Python Search Path
>>>sys.path
['', '/Library/Python/2.6/site-packages/ipython-0.10.1-py2.6.egg', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Python/2.6/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode']

No comments: