Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

add file to tar with chmod +x python

I have tar.gz file like:

tmp/
tmp/picture/
tmp/picture/1.jpg

I want to add to this tar.gz file with python file to tmp/logger.sh with chmod +x

How can I do that ?

import tarfile
with tarfile.open('test.tar.gz','w') as f:
    f.add('logger.sh' , arcname='/tmp/logger.sh')

That give me tar file /tmp/logger.sh file but remove the rest of files that was in the tar file + I can't set chmod +x to this file


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The absolutely simplest solution is to (temporarily?) chmod the file before adding it.

As you already discovered, 'w' mode will overwrite any existing file. To update an existing archive, you want to open the file in 'a' mode instead.

However, unfortunately, the tarfile library does not support opening a gz file in a mode. You can do this if you have an uncompressed file:

import tarfile

def chmodx(tarinfo):
    tarinfo.mode = int('0755', base=8)
    return tarinfo

with tarfile.open('test.tar', 'a'):
    f.add('logger.sh' , arcname='/tmp/logger.sh', filter=chmodx)

The nature of gz compression is such that you probably simply want to uncompress the file, update it, and then recompress, rather than do it all in one go. Ideally, you'd want to do this in memory, but that's problematic if the uncompressed tar file is large.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...