我想要一个可以为我的所有重要文件创建备份的程序。(下面测试环境为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. node模拟http服务器session机制-我们到底能走多远系列(36)

    我们到底能走多远系列(36) 扯淡: 年关将至,总是会在一些时间节点上才感觉时光飞逝,在平时浑浑噩噩的岁月里都浪费掉了太多的宝贵.请珍惜! 主题:      我们在编写http请求处理和响应的代码的时 ...

  2. Linux虚拟主机通过程序实现二级域名绑定到子目录

    虚拟主机中CP控制台不支持将二级域名绑定到子目录的功能,用户可以通过程序实现将二级域名绑定到子目录. 有两种方法将二级域名绑定到子目录: 1. 配置.htaccess, 通过伪静态代码实现.具体实现方 ...

  3. leetcode之反转链表

    原文链接:点击打开链接 Reverse a singly linked list A linked list can be reversed either iteratively or recursi ...

  4. HDU 5957 Query on a graph

    HDU 5957 Query on a graph 2016ACM/ICPC亚洲区沈阳站 题意 \(N(N \le 10^5)\)个点,\(N\)条边的连通图. 有\(M \le 10^5\)操作: ...

  5. zf2 中 new Express 的用法

    在使用联表查询时,如查联表条件有多个也可以,但是连接条件在zf2中会自动给列加``符号,所以要加像id = 1 这样的,他自动给1加``就无示执行了,这时候可以使用new Express(''),他里 ...

  6. 什么是HTML、XML和XHTML

    (1)XMLXML是The Extensible Markup Language(可扩展标识语言)的简写.目前推荐遵循的是W3C于2000年10月6日发布的XML1.0,参考(www.w3.org/T ...

  7. Linux驱动设计—— 内核模块(一)

    Linux内核理论基础 组成Linux内核的5个子系统:进程调度(SCHED)/内存管理(MM)/虚拟文件系统(VFS)/网络接口(NET)/进程间通信(IPC). 进程调度(SCHED) 在设备驱动 ...

  8. Java——匿名内部类

     /* * 匿名内部类,  就是内部类的简写形式. * *  必须有前提: *  内部类必须继承或者实现一个外部类或者接口. * 匿名内部类其实就是一个子类对象. * * 格式:new 父类or接 ...

  9. ssh命令:使用密钥文件进行登陆

    在win上面可以使用XSHELL来登录类似于亚马逊这样的安全服务器,在mac上面就可以使用系统自带的命令工具来连接 1.使用命令 ssh -i key.pem [server] 如下: ssh -i  ...

  10. 9款精致HTML5/jQuery日历时钟控件源码下载(源码请见百度云) 链接:http://pan.baidu.com/s/1geIXe75 密码:7m4a

    现在的网页应用越来越丰富,我们在网页中填写日期和时间已经再也不用手动输入了,而是使用各种各样的日期时间选择控件,大部分样式华丽的日期选择和日历控件都是基于jQuery和HTML5的,比如今天要分享的这 ...