Pyhon之简单备份命令学习

#!/usr/bin/python
# Filename: backup_ver1.py
#coded by swaroop, recoded by lewis liu
import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['/home/lc/max', '/home/lc/python_projects']
# 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 = '/home/lc/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
# if you want to don`t want to capture the detail of zip command,you can use "
zip -qr '%s' %s"
zip_command = "zip -r '%s' %s" % (target, ' '.join(source)) # Run the backup if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED'

使用的模块:os、time

重要参数:source和targettarget_dir+time+.zip

注意事项:

Windows中使用反斜杠(\)来作为目录分隔符的,而Python则是用反斜杠表示转义符!
所以,你得使用转义符来表示反斜杠本身或者使用自然字符串。

例如,'C:\\Documents'r'C:\Documents'不是'C:\Documents'

改进版本如下:

#coding=utf-8
#!/usr/bin/python
# Filename: backup_ver3.py
#coding=utf-8 在ubuntu中在这行放入编码说明不行,只有在文首才行
 

import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['/home/lc/max', '/home/lc/python_projects']
# 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 = '/home/lc/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'#path update
else:
    target = today + os.sep + now + '_' + \
    comment.replace(' ', '_') + '.zip'#在today路径下新建now子文件夹,再在这个子文件夹下创建一个_comment.zip文件

# 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'
View Code

 

posted @ 2015-04-01 20:53  LewisLiu  阅读(167)  评论(0)    收藏  举报