python笔记2

三、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/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/23937368/viewspace-1056201/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值