python筆記2

oxoxooxx發表於2011-11-07
三、python指令碼示例
---------------------------------------------------
DEMO ONE:
建立一個備份重要檔案的程式:
1.python 如何呼叫系統命令,並分析輸出
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
os.system(zip_command)

示例:
import os
source_dir = ['/home/tk']
target_dir= '/home/wangmin'

if not os.path.exists(target_dir):
os.mkdir(target_dir)
print 'create dir succefully!'

gzip_command = "zip -qr '%s' %s" % (target_dir, ' '.join(source_dir))

if os.system(gzip_command) == 0:
print 'backup succefully to ',target_dir
else:
print 'backup failed'
---------------------------------------------------

DEMO TWO:
1.讀取檔案並列印
2.對引數進行判斷
以--開頭:
若為version列印版本資訊
若為help列印幫助資訊
否則:
遍歷所有引數指向的檔案並列印。
---------------------------------------------------
#!/usr/bin/python
class fileprocess:
def readfile(filename):
f=file(filename)
while true:
line=f.readline()
if len(line) == 0:
break
print line,
f.close()
#process options
if len(sys.argv)<2:
print "no action to do "
sys.exit()

if sys.argv[1].startwith('--'):
option=sys.argv[1][2:]
if option == 'version':
print "the version is Version 1.2"
if option == 'help':
print '''This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help'''
else:
print "unknow options"
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)


def repeat():
return lambda s:s*n

myfun=repeat(2)

print myfun('hello')
---------------------------------------------------[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/23937368/viewspace-1056201/,如需轉載,請註明出處,否則將追究法律責任。

相關文章