- 光说不练假把式,用小脚本学习Python。一个简单的备份脚本。# ! /usr/bin / env python3# - *- coding: utf - 8 - *-#
- for backup import os import time#需要备份的目录source = [' /
- var / log / history / ',
- ' /
- var / log / httpd / ']#保存备份的目录target_dir = ' / tmp / 'today_dir = target_dir + time.strftime(' % Y % m % d') time_dir = time.strftime("%H%M%S")'''os.sep:主要是为了跨平台,根据系统的不同,分隔符不一样 >>> os.sep' / ''''touch = today_dir + os.sep + time_dir + '.zip'print(touch)'''zip : -q: 执行时不显示压缩过程 - r: 对该目录递归' '.join(source) : 将列表转换位字符串 >>> sou = ['s', 'y', 'l'] >>> s = ' '.join(sou) >>> print(s) s y l'''zip_command = "zip -qr " + touch + ' ' + ' '.join(source) print(zip_command)'''将target、source及" zip - qr "通过字符串连接符号相连接,得到command命令行,再调用os.system()函数运行command命令,如果成功,返回0,否则返回错误号os.path.exits():exits()函数的功能就是检查该系统中,是否存在指定路径的文件或文件夹存,没有返回False(False 等于 0),有则返回True(True 不等于 0) >>> os.path.exists(' / ') True >>> os.path.exists(' / true') False'''
- if os.path.exists(today_dir) == 0 : os.mkdir(today_dir) if os.system(zip_command) == 0 : print('Successful backup')
- else: print('Backup Failed')
来源: http://www.bubuko.com/infodetail-1864117.html