python - 如何使用tarfile实现目录过滤的打包文件

查看:515
本文介绍了python - 如何使用tarfile实现目录过滤的打包文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

如何在不使用python调用shell的情况下,就是不使用subprocess,os.system等调用tar命令情况下,使用python标准库的tarfile实现tar中--exclude的效果,例如:

tar -cvpzf /media/sda7/backup.tgz --exclude=/proc --exclude=/lost+found --exclude=/mnt --exclude=/sys --exclude=/media /

这里对目录/下的/proc/lost+found,/mnt,/sys/media目录进行过滤,并其结果打包在/media/sda7/backup.tgz文件中。
下面的解决方案是可以的,但是对于/home/sky目录下的文件打包就不可以了:

#!/usr/bin/env python

import tarfile

exclude_names = ['build']
def filter_func(tarinfo):
    if tarinfo.name not in exclude_names and tarinfo.isdir():
        return None
    else:
        return tarinfo
t = tarfile.open("backup.tgz", "w:gz")
t.add("/home/sky", filter=filter_func)

比如我在sky目录下有1个build目录,只对其进行打包的话,结果如下:

sky@debian:~$ tar -tvf backup.tgz 

可以发现目录下完全没有文件。

解决方案

TarFile.add(name, arcname=None, recursive=True, exclude=None, *, filter=None)
Add the file name to the archive. name may be any type of file (directory, fifo, symbolic link, etc.). If given, arcname specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting recursive to False. If exclude is given, it must be a function that takes one filename argument and returns a boolean value. Depending on this value the respective file is either excluded (True) or added (False). If filter is specified it must be a keyword argument. It should be a function that takes a TarInfo object argument and returns the changed TarInfo object. If it instead returns None the TarInfo object will be excluded from the archive. See Examples for an example.

利用filter参数设定filter函数,filter函数接收TarInfo对象,在filter函数内判断tarinfo对象的类型和名字,如果不符合要求就不返回传入的对象。

import tarfile
exclude_names = ['proc', 'lost+found', 'mnt', 'sys', 'media']
def filter_func(tarinfo):
    if tarinfo.name in exclude_names and tarinfo.isdir():
        return None
    else:
        return tarinfo
t = tarfile.open("/media/sda7/backup.tgz", "w:gz")
t.add("/", filter=filter_func)

这篇关于python - 如何使用tarfile实现目录过滤的打包文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆