我想要一个可以为我的所有重要文件创建备份的程序。(下面测试环境为python2.7)

1.backup_ver1.py

#!/usr/bin/python
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/esun']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'

运行结果

[root@host python]# ./backup_ver1.py
Successful backup to /mnt/e/backup/20160107150139.zip
 

zip命令有一些选项和参数。-q选项用来表示zip命令安静地工作。-r选项表示zip命令对目录递归地工作,即它包括子目录以及子目录中的文件。两个选项可以组合成缩写形式-qr。选项后面跟着待创建的zip归档的名称,然后再是待备份的文件和目录列表。我们使用已经学习过的字符串join方法把source列表转换为字符串。最后,我们使用os.system函数 运行 命令,利用这个函数就好像在 系统 中运行命令一样。即在shell中运行命令——如果命令成功运行,它返回0,否则它返回错误号。

2.backup_ver2.py

#!/usr/bin/python
# Filename: backup_ver2.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/esun']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# The name of the zip file
target = today + os.sep + now + '.zip'
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'

运行结果

[root@host python]# ./backup_ver2.py
Successfully created directory /mnt/e/backup/20160107
Successful backup to /mnt/e/backup/20160107/105442.zip
 

两个程序的大部分是相同的。改变的部分主要是使用os.exists函数检验在主备份目录中是否有.以当前日期作为名称的目录。如果没有,我们使用os.mkdir函数创建。注意os.sep变量的用法——这会根据你的操作系统给出目录分隔符,即在Linux、Unix下它是'/',在Windows下它是'\\',而在Mac OS下它是':'。使用os.sep而非直接使用字符,会使我们的程序具有移植性,可以在上述这些系统下工作。

3. backup_ver4.py

#!/usr/bin/python
# Filename: backup_ver4.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/esun', '/etc']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'
# Notice the backslash!
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'

运行结果

[root@host python]# ./backup_ver4.py
Enter a comment --> test1 Successful backup to /mnt/e/backup/20160107/111406_test1.zip
 

我们使用raw_input函数得到用户的注释,然后通过len函数找出输入的长度以检验用户是否确实输入了什么东西。如果用户只是按了回车(比如这只是一个惯例备份,没有做什么特别的修改),那么我们就如之前那样继续操作。

4.总结:对于大多数用户来说,第四个版本是一个满意的工作脚本了,但是它仍然有进一步改进的空间。比如,你可以在程序中包含 交互 程度——你可以用-v选项来使你的程序更具交互性。我还希望有的一个优化是使用tar命令替代zip命令。如:tar = 'tar -cvzf %s %s -X /home/swaroop/excludes.txt' % (target, ' '.join(srcdir))。最理想的创建这些归档的方法是分别使用zipfile和tarfile。它们是Python标准库的一部分,可以供你使用。使用这些库就避免了使用os.system这个不推荐使用的函数,它容易引发严重的错误。

Python编写一个Python脚本的更多相关文章

  1. python编写文件统计脚本

    python编写文件统计脚本 思路:用os模块中的一些函数(os.listdir().os.path.isdir().os.path.join().os.path.abspath()等) 实现功能:显 ...

  2. 用Python编写一个简单的Http Server

    用Python编写一个简单的Http Server Python内置了支持HTTP协议的模块,我们可以用来开发单机版功能较少的Web服务器.Python支持该功能的实现模块是BaseFTTPServe ...

  3. 使用 python 编写一个授权登录验证的模块

    使用 python 编写一个授权登录验证的模块 我们编写的思路: 1.登录的逻辑:如果用户名和密码正确,就返回 token . 2.生成 token 的逻辑,根据用户名,随机数,当前时间 + 2 小时 ...

  4. python编写DDoS攻击脚本

    python编写DDoS攻击脚本 一.什么是DDoS攻击 DDoS攻击就是分布式的拒绝服务攻击,DDoS攻击手段是在传统的DoS攻击基础之上产生的一类攻击方式.单一的DoS攻击一般是采用一对一方式的, ...

  5. 编写一个BAT脚本协助运维人员遇到问题时候调测数据库是否有效连接成功的操作攻略

    简单摘要: 1.内网系统出现故障需要排查 2.运维人员不熟悉数据库操作,没法通过连接数据库和执行SQL语句的方式排查数据库及数据是否正常 3.解决方案:编写一个bat脚本,运维人员双击运行即可.   ...

  6. 工程师技术(五):Shell脚本的编写及测试、重定向输出的应用、使用特殊变量、编写一个判断脚本、编写一个批量添加用户脚本

    一.Shell脚本的编写及测 目标: 本例要求两个简单的Shell脚本程序,任务目标如下: 1> 编写一个面世问候 /root/helloworld.sh 脚本,执行后显示出一段话“Hello ...

  7. shell编写一个判断脚本

                                                              shell编写一个判断脚本 4.1问题 本例要求在虚拟机server0上创建/roo ...

  8. 从0开始的Python学习013编写一个Python脚本

    通过之前的学习我们已经了解了Python的很多基础运用了,现在我们尝试着做一个有使用价值的小脚本. 问题 需求: 我想要一个可以给我备份重要文件的程序. 需求分析: 首先文件是有存储路径,文件的路径和 ...

  9. python+pytest接口自动化(12)-自动化用例编写思路 (使用pytest编写一个测试脚本)

    经过之前的学习铺垫,我们尝试着利用pytest框架编写一条接口自动化测试用例,来厘清接口自动化用例编写的思路. 我们在百度搜索天气查询,会出现如下图所示结果: 接下来,我们以该天气查询接口为例,编写接 ...

随机推荐

  1. [转]CentOS6.3安装JDK和环境配置

    转自:http://www.linuxidc.com/Linux/2012-09/70780.htm 1.CentOS默认情况下,会安装OpenOffice之类的软件,这些软件需要Java的支持,默认 ...

  2. CSS 阴影怎么写?

    只有CSS3才zh支持阴影效果,ke可以用如下写法:.shadow {-webkit-box-shadow:1px 1px 3px #292929;-moz-box-shadow:1px 1px 3p ...

  3. JQ添加移除css样式--转载 心存善念

    我们常常要使用Javascript来改变页面元素的样式.其中一种办法是改变页面元素的CSS类(Class),这在传统的Javascript里,我们通常是通过处理HTML Dom的classname特性 ...

  4. openni和骨架追踪 rviz查看---34

    原创博客:转载请标明出处:http://www.cnblogs.com/zxouxuewei/ 1.安装深度相机的NITE. 首先下载NITE-Bin-Dev-Linux-x64-v1.5.2.23, ...

  5. Codeforces Round #146 (Div. 2)

    A. Boy or Girl 模拟题意. B. Easy Number Challenge 筛素数,预处理出\(d_i\). 三重循环枚举. C. LCM Challenge 打表找规律. 若\(n\ ...

  6. springMvc源码学习之:spirngMvc的拦截器使用

    SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理.比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306 那 ...

  7. Linux 挂载新硬盘

    Linux 的硬盘识别 在 /dev/ 下建立相应的设备文件.如 sda 表示第一块 SCSI 硬盘 hda 表示第一块 IDE 硬盘(即连接在第一个 IDE 接口的 Master 口上) scd0 ...

  8. EasyUI之DataGrid使用

    http://blog.csdn.net/liovey/article/details/9173931 背景介绍: 原 先项目采用普通的jsp页面来做为前端显示,用户体验差,并且为了实现某一种效果需要 ...

  9. SVG 箭头线绘制

    SVG并没有提供原生的Arrow标签,这就需要自己的组合了,通过marker标签和path标签可以完美的模仿出箭头线,无论需要多少个箭头线,只需引用同一个marker即可: <svg id=&q ...

  10. 谷歌 analytics.js 简要分析

    下面是部分翻译过的JS,看起来好看些.   (function () { function setHref(a, b) { return a.href = b; } function setName( ...