#!/usr/bin/env python
#-*-Coding:utf-8-*-
# Filename:bak_ws.py
Import OS
Import time
Import Sys
# 1, the files and directories to is backed up is specified in a list
# source = ['/home/my_prog ', '/usr/local/mydata/']
print '-' * 32
Source=[]
print ' The command line arguments is: '
For I in SYS.ARGV:
Print I
if i = = Sys.argv[0]:
Continue
Source.append (i)
print '-' * 32
# Check input, if error app exit
If Len (source) = = 0:
print ' should input the files or directories, like
Python bak.py/home/my_prog/usr/local/mydata/... "
Exit ()
Else
print ' Some files or directorier is saved into. tar.gz format: '
Print Source
# If You is using Windows, use
# source=[r ' c:/documents ', R ' d:/work ') or
# something like that
# 2, the backup must is stored in a main backup directory
# Remember to the change of this-what are you'll be using
Target_dir = '/data/backup/'
# Determine if the directory exists
If not os.path.exists (Target_dir):
# Create a multilevel directory
Os.makedirs (Target_dir)
# 3, the files is backed up into a tar file
# 4, the name of subdirectory and tar file
Today = Time.strftime ('%y%m%d ')
now = Time.strftime ('%h%m%s ')
# Take a comment from the user to create the name of the tar file
Comment = raw_input (' Enter a Comment: ')
If len (comment) = = 0:
target = Target_dir + today + os.sep + Now + '. tar.gz '
Else
target = Target_dir + today + os.sep + comment.replace ("', '-') + ' _ ' + Now + '. tar.gz '
# Create The subdirectory if it isn ' t already there
If not os.path.exists (target_dir+today):
Os.mkdir (Target_dir+today)
print ' Successfully created directory ', today
# 5, We use the tar command (in Unix/linux) to put the files in a tgz archive
Tar_command = "tar-zcf%s%s"% (target, ". Join (source)")
# Run The Backup
If Os.system (tar_command) = = 0:
print ' successful backup to ', target
Else
print ' Backup failed. '
# End
This article is from the "Sanctuary of Calm" blog, please make sure to keep this source http://mastters.blog.51cto.com/6516495/1553313
Python Backup Script