1. #!/usr/local/python251/bin/python
  2. import sys
  3. import os
  4. import time
  5.  
  6. #若是没有输入参数,则会提示而且中断。
  7. if len(sys.argv[1:]) == 0:
  8.     print 'please input source file or directory.'
  9.     sys.exit()
  10. else:
  11.     source = ' '.join(sys.argv[1:])#按照固定的格式组成一个字符串
  12.  
  13. target_dir = '/home/handaoliang/backup/'+time.strftime('%Y%m%d')#目标文件夹
  14. #若是目标文件夹不存在,则进行建立,而且打印结果
  15. if not os.path.exists(target_dir):
  16.     os.mkdir(target_dir)#create directory.
  17.     print target_dir,'is successfully created...'
  18. #要求输入注释
  19. comment = raw_input('please input a comment:')
  20. #若是注释为家,则默认文件名为时分秒格式。
  21. if len(comment) == 0:
  22.     target_file_name = target_dir+os.sep+time.strftime('%H%M%S')+'.tar.gz'
  23. else:
  24.     target_file_name = target_dir+os.sep+time.strftime('%H%M%S')+'_'+\
  25.         comment.replace(' ','_')+'.tar.gz'
  26. #组建tar命令串
  27. tar_command = 'tar czvf %s %s'%(target_file_name,source)
  28. #经过os.system把此命令跑一遍,并根据返回结果看是否备份成功。
  29. if os.system(tar_command) == 0:
  30.     print 'sucessfully backup:',target_file_name
  31. else:
  32.     print 'backup FAILED'
  33.