使用subprocess.call在python中压缩文件

2024-10-01 00:14:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我的服务器有点问题。在

所以故事是: 我有一个NAS来处理域中的电子邮件。它工作得很好,但是它没有为电子邮件提供任何备份软件,但是它包含的邮箱有点奇怪。在

它包含在用户的主目录中,比如“/home/user123/.Mailbox”

所以如果我想收集这些邮箱并存档,我必须编写一点代码。在

问题是虽然它上面有一种Linux,但是它没有bash但是sh没有for循环。在

另一方面,它有python模块,我开始在里面写一些脚本,但是后来我坚持。。。在

当我想使用ZIP打包和压缩文件时,我注意到如果我通过一个变量传递ZIP命令的参数,它就不能处理它们之间的空格。在

有人能给我一个解决办法吗?在

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from os import walk,path
import subprocess
import datetime

sourcepath="/home/"
savepath="/backups"
foldername=[]
tarparams=''
dt=str(datetime.date.today())

## get to know the directories in /home    
for (dirpath,dirnames,filenames) in walk(sourcepath):
    foldername.extend(dirnames)
    break
##

## check if the save path exists and if it does create the parameters of the compression
if not path.exists(savepath):
    print "Save path does not exist"
    exit()
else:
    for userhomedir in foldername:
        if path.exists(sourcepath+userhomedir+"/.Maildir"):
#           tarparams=tarparams+'"'+sourcepath+userhomedir+"/.Maildir"+'",'
            tarparams=tarparams+sourcepath+userhomedir+"/.Maildir "
        else:
        None
##

## call the zip command and compress the mailboxes with the highest compression
#subprocess.call(["zip","-r","-9",savepath+"/mailbkp-"+dt,tarparams])
subprocess.call(["zip","-r","-9",savepath+"/mailbkp-"+dt]+tarparams.split())
##

提前谢谢你。:-)


Tags: thepathinimporthomeforifexists