python的tar模块和exclude方法的行为

时间:2017-10-02 17:30:11

标签: python tar

我需要强制python的tar模块在shell中作为tar命令工作,问题出在" exclude"方法

shell中的tar示例(它按设计工作,我们添加了exclude和nginx.conf从归档中排除):

xasan@dell [python]$ find /etc/nginx/* -iname 'nginx.conf'
/etc/nginx/nginx.conf

xasan@dell [python]$ tar czvf /tmp/test.tar.gz --exclude nginx.conf 
/etc/nginx/proxy_params 
/etc/nginx/fastcgi.conf 
/etc/nginx/mime.types 
/etc/nginx/win-utf 
/etc/nginx/koi-win 
/etc/nginx/sites-available/ 
/etc/nginx/sites-available/default 
/etc/nginx/koi-utf 
/etc/nginx/fastcgi_params 
/etc/nginx/uwsgi_params 
/etc/nginx/snippets/ 
/etc/nginx/snippets/fastcgi-php.conf 
/etc/nginx/snippets/snakeoil.conf 
/etc/nginx/scgi_params 
/etc/nginx/conf.d/ 
/etc/nginx/sites-enabled/ 
/etc/nginx/sites-enabled/default

xasan@dell [python]$ tar tzvf /tmp/test.tar.gz | grep 'nginx.conf$'
xasan@dell [python]$

让我们对python模块做同样的事情:

import tarfile                                                                                                               

excl='nginx.conf'                                                                                                            
what='/etc/nginx'                                                                                                       

tar=tarfile.open('/tmp/test.tar.gz','w:gz')                                                                                  

tar.add(what,exclude=lambda x: True if what in excl else False)                                                              
tar.close()

检查。我们可以看到排除不像在本地tar中那样工作

xasan@dell [python]$ tar tzf /tmp/test.tar.gz | grep -i 'nginx.conf$'
etc/nginx/nginx.conf

我已经尝试将所有数据存储到我想要存档的目录中,然后使用排除对象的完整路径名称......它有效,但不方便。

类似的东西:

import tarfile                                                                                                               
import os 

excl='nginx.conf'                                                                                                            
what='/etc/nginx'
lst_of_dirs_1lvl=os.listdir(what) # list of content in the 1st level of  dir 

tar=tarfile.open('/tmp/test.tar.gz','w:gz')                                                                                  

for i in lst_of_dirs_1lvl:                                                                                                   
    full_path_obj='{0}/{1}'.format(what,i) # full path to the object which we're adding to archive                                                                             
    tar.add(full_path_obj,exclude=lambda x: True if i in excl else False)                                                    
tar.close()

归档中没有我们的排除文件,因此可以正常运行:

xasan@dell [python]$ tar tzf /tmp/test.tar.gz | grep -i 'nginx.conf$'
xasan@dell [python]$

但是在这种情况下,我们只能排除第一个嵌套级别中的对象,因此我们需要在存档的dir中构建文件树,然后在该树中运行......所以它不是一个好的解决方案。 / p>

0 个答案:

没有答案