>>> from string import Template
>>> s = Template('There are ${howmany} ${lang} Quotation Symbols')
>>> print s.substitute(lang='Python',howmany=3)
There are 3 Python Quotation Symbols
7.函数装饰器(方便操作日志等)
from time import ctime,sleep
def tsfunc(func):
def wrappedFunc():
print '[%s] %s() called' % (ctime(),func.__name__)
return func()
return wrappedFunc
@tsfunc
def foo():
pass
foo()
sleep(4)
for i in range(2):
sleep(1)
foo()
输出结果
---------- python ----------
[Thu Dec 17 15:44:46 2009] foo() called
[Thu Dec 17 15:44:51 2009] foo() called
[Thu Dec 17 15:44:52 2009] foo() called
---------------------------------------------------
小例子
'writeOrRead.py'
import os
ls = os.linesep
print "Enter file name: \n"
fname = raw_input('>')
isOk = False
# get filename
while True:
if os.path.exists(fname):
print "read "+ fname
print '-----------------------'
break
else:
isOk = True
break
if(isOk):
# get file content(text) lines
all = []
print "\nEnter lines('.' by itself to quit).\n"
print "write content:"
# loop until user terminates input
while True:
entry = raw_input('>')
if entry == '.':
break
else:
all.append(entry)
# write lines to file with proper line-ending
fobj = open(fname,'w')
fobj.writelines(['%s%s' % (x,ls) for x in all])
fobj.close()
print 'DONE!'
else:
# read and display text file
try:
fobj = open(fname,'r')
except IOError,e:
print fname+" file open error:",e
else:
#display contents to the screen
for eachLine in fobj:
print eachLine,
fobj.close()