Python编写一个Python脚本
我想要一个可以为我的所有重要文件创建备份的程序。(下面测试环境为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脚本的更多相关文章
- python编写文件统计脚本
python编写文件统计脚本 思路:用os模块中的一些函数(os.listdir().os.path.isdir().os.path.join().os.path.abspath()等) 实现功能:显 ...
- 用Python编写一个简单的Http Server
用Python编写一个简单的Http Server Python内置了支持HTTP协议的模块,我们可以用来开发单机版功能较少的Web服务器.Python支持该功能的实现模块是BaseFTTPServe ...
- 使用 python 编写一个授权登录验证的模块
使用 python 编写一个授权登录验证的模块 我们编写的思路: 1.登录的逻辑:如果用户名和密码正确,就返回 token . 2.生成 token 的逻辑,根据用户名,随机数,当前时间 + 2 小时 ...
- python编写DDoS攻击脚本
python编写DDoS攻击脚本 一.什么是DDoS攻击 DDoS攻击就是分布式的拒绝服务攻击,DDoS攻击手段是在传统的DoS攻击基础之上产生的一类攻击方式.单一的DoS攻击一般是采用一对一方式的, ...
- 编写一个BAT脚本协助运维人员遇到问题时候调测数据库是否有效连接成功的操作攻略
简单摘要: 1.内网系统出现故障需要排查 2.运维人员不熟悉数据库操作,没法通过连接数据库和执行SQL语句的方式排查数据库及数据是否正常 3.解决方案:编写一个bat脚本,运维人员双击运行即可. ...
- 工程师技术(五):Shell脚本的编写及测试、重定向输出的应用、使用特殊变量、编写一个判断脚本、编写一个批量添加用户脚本
一.Shell脚本的编写及测 目标: 本例要求两个简单的Shell脚本程序,任务目标如下: 1> 编写一个面世问候 /root/helloworld.sh 脚本,执行后显示出一段话“Hello ...
- shell编写一个判断脚本
shell编写一个判断脚本 4.1问题 本例要求在虚拟机server0上创建/roo ...
- 从0开始的Python学习013编写一个Python脚本
通过之前的学习我们已经了解了Python的很多基础运用了,现在我们尝试着做一个有使用价值的小脚本. 问题 需求: 我想要一个可以给我备份重要文件的程序. 需求分析: 首先文件是有存储路径,文件的路径和 ...
- python+pytest接口自动化(12)-自动化用例编写思路 (使用pytest编写一个测试脚本)
经过之前的学习铺垫,我们尝试着利用pytest框架编写一条接口自动化测试用例,来厘清接口自动化用例编写的思路. 我们在百度搜索天气查询,会出现如下图所示结果: 接下来,我们以该天气查询接口为例,编写接 ...
随机推荐
- ZOJ 1216 Deck
原题链接 题目大意:1/2+1/4+1/6+…1/n 解法:直接累加即可. 参考代码: #include<stdio.h> int main(){ printf("# Cards ...
- 关于C中scanf()函数读取字符串的问题
#include <stdio.h> int main(void) { ]; scanf("%s", s_name); printf("Hello, %s!\ ...
- makefile--目录搜索(八)
在一个较大的工程中,一般会将源代码和二进制文件(.o 文件和可执行文件)安排在不同的目录来进行区分管理.这种情况下,我们可以使用 make 提供的目录搜索依赖文件功能(在指定的若干个目录下自动搜索依赖 ...
- makefile--统一目标输出目录 (六)
原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuewei/ 上一节我们把规则单独提取出来,方便了Makefile的维护,每个模块只需要给出关于自己的一些变量 ...
- Prim求解最小生成树
#include "ljjz.h" typedef struct edgedata /*用于保存最小生成树的边类型定义*/ { int beg,en; /*beg,en是边顶点序号 ...
- JavaWeb学习记录(二十四)——获取插入数据后,自动生成的id值
public Integer insertObjects(final Goods entity) { // 定义sql语句 final String sql1 = "inser ...
- 第n小的质数
总时间限制: 1000ms 内存限制: 65536kB 描述 输入一个正整数n,求第n小的质数. 输入 一个不超过10000的正整数n. 输出 第n小的质数. 样例输入 10 样例输出 29 代碼 ...
- HDU 2083 简易版之最短距离 --- 水题
HDU 2083 简易版之最短距离 /* HDU 2083 简易版之最短距离 */ #include <cstdio> #include <algorithm> using n ...
- 通过laravel理解IoC(控制反转)容器和DI(依赖注入)
原文地址: http://www.insp.top/learn-laravel-container ,转载务必保留来源,谢谢了! 容器,字面上理解就是装东西的东西.常见的变量.对象属性等都可以算是容器 ...
- 【P1835】小红花
很简单的题,然而我没想到,在NOIP上怎么办嘛QAQ 话说这题不知道怎么分类啊……先扔到玄学里边把…… 原题: Fj在圣诞节来临之际,决定给他的奶牛发一些小红花.现在Fj一共有N头奶牛,这N头牛按照编 ...