使用python在内存中的zip文件中创建符号链接 [英] Create symlink inside a zipfile in memory using python

查看:114
本文介绍了使用python在内存中的zip文件中创建符号链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在内存中创建zipfile并在zipfile中包含符号链接的方法. 到目前为止,我已经发现此

I am looking for a way to create a zipfile in memory and include a symlink inside the zipfile. So far I have found this link and try the following code:

from zipfile import ZipInfo
from zipfile import ZipFile
from zipfile import ZIP_DEFLATED, ZIP_STORED
from cStringIO import StringIO
import codecs


buf = StringIO()
zipfile = ZipFile( buf,'w')

zipinfo = ZipInfo()
zipinfo.filename = u'bundle/'
zipinfo.compress_type = ZIP_STORED
zipinfo.external_attr = 040755 << 16L # permissions drwxr-xr-x
zipinfo.external_attr |= 0x10 # MS-DOS directory flag
zipfile.writestr(zipinfo, '')


path = u'bundle/test.txt'
zipinfo = ZipInfo(path)
zipinfo.compress_type = ZIP_DEFLATED
zipinfo.external_attr = 0644 << 16L # permissions -r-wr--r--
zipfile.writestr(zipinfo, u'Test content')

dest = path

#create symbolic link (success)
zipinfo = ZipInfo()
zipinfo.filename = u'test_link.txt'
zipinfo.external_attr |= 0120000 << 16L # symlink file type
zipinfo.compress_type = ZIP_STORED
zipfile.writestr(zipinfo, dest)


#create symbolic link (failed)
zipinfo = ZipInfo()
zipinfo.filename = u'bundle1/test_link.txt'
zipinfo.external_attr |= 0120000 << 16L # symlink file type
zipinfo.compress_type = ZIP_STORED
zipfile.writestr(zipinfo, dest)

for info in zipfile.infolist():
    print u'filename %s' %info.filename
    print u'external_attr %s' %info.external_attr
    print u'header_offset %s' %info.header_offset
    print u'file_size %s' %info.file_size
    print u'crc %s' %info.CRC 
    print u'\n\n'


zipfile.close()
buf.reset()
with codecs.open('test.zip', 'w') as f:
    f.write(buf.getvalue())
buf.close()

如果链接直接位于unzip文件夹的根目录下,则上面的代码能够成功创建符号链接,否则将失败(解压缩后,如果我尝试打开符号链接文件bundle1/text1.txt,它会返回警告

The code above was able to create symlink successfully if the link is located directly under the root of unzip folder otherwise it is failed (after unzip if I try to open the symlink file bundle1/text1.txt, and it return an warning

该操作无法完成,因为 找不到"test_link.txt".

The operation can’t be completed because the original item for "test_link.txt" can’t be found.

能帮我如何使symlink bundle1/test_link.txt正常工作吗?

Could you please help me how to get symlink bundle1/test_link.txt works properly?

推荐答案

如果在bundle1中创建指向bundle/test.txt的符号链接,则目标必须位于bundle1/bundle/test.txt中.符号链接通常总是相对于它们自己的路径(除非它们以/开头)

If you create a symlink in bundle1 that points to bundle/test.txt, the target would have to be located in bundle1/bundle/test.txt. Symlinks alre always relative to their own path (unless of course they start with a /)

因此,要执行此操作,您需要将链接目标更改为../bundle/test.txt.

So to make this work, you need to change the link destination to ../bundle/test.txt.

这篇关于使用python在内存中的zip文件中创建符号链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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