欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python使用7z解压软件备份文件脚本分享

程序员文章站 2023-08-14 09:45:56
要求安装: 1.python2.7z解压软件 backup_2.py 复制代码 代码如下:# filename: backup_2.py '''backup fil...

要求安装:

1.python
2.7z解压软件

backup_2.py

复制代码 代码如下:

# filename: backup_2.py

'''backup files.
    version: v2, based on python 3.3
    usage: backup.py -s:"dir1|dir2|..." -t:"target_dir" [-c:"comment"]
        -s: the source directories.
        -t: the target directory.
        -c: optional, any comment.
    examples:
        backup.py -s:"c:\\src\\f1|c:\\src\\f2|c:\\src\\f 3" -t:"c:\\backup"
        backup.py -s:"c:\\src\\f 3" -t:"c:\\backup" -c:"for sample"'''

import os
import sys
import time

# read sys.argv
print(sys.argv)
if len(sys.argv) < 2:
    print(__doc__)
    sys.exit()

source=[]
target_dir=''
comment=''
for arg in sys.argv:
    if arg.startswith('-s:'):
        source=arg[3:].split('|')
        print(source)
    elif arg.startswith('-t:'):
        target_dir=arg[3:]+os.sep
        print(target_dir)
    elif arg.startswith('-c:'):
        comment=arg[3:]
        print(comment)

for i in range(0, len(source)):
    source[i] = "\"" + source[i] + "\""
    print(source[i])

# make the file name with the time and comment
today=target_dir+time.strftime('%y%m%d')
now=time.strftime('%h%m%s')

if len(comment)==0: # check if a comment was entered
    target=today+os.sep+now+'.7z'
else:
    target=today+os.sep+now+'_'+\
            comment.replace(' ','_')+'.7z'

# create the subdirectory by day
if not os.path.exists(today):
    os.mkdir(today) # make directory
    print('successfully created directory',today)

# zip command
zip_command="7z a %s %s" %(target,' '.join(source))
print(zip_command)

# run the backup
if os.system(zip_command)==0:
    print('successful backup to',target)
else:
    print('backup failed')