当我使用 tar cfz cl.tar.gz Sources
生成 tar.gz 文件时,与 python shutil.make_archive ( "py", "gztar", "Sources"相比)
,我得到不同的结果:
$ tar -tf cl.tar.gz | head -3
algorithm/
aligned_storage.hpp
algorithm/cxx11/
$ tar -tf py.tar.gz | head -3
./algorithm/
./aligned_storage.hpp
./algorithm/cxx11/
大多数时候这没有什么区别;但如果您在解压缩时传递 --strip-components
,则两个存档的行为会有所不同。
我真的很想从 python 代码中获得与从 shell 脚本中获得的结构相同的结构,但我不太确定如何做到这一点。我在 Mac OS 10.8.1 上使用 Python 2.7.3,如果这有影响的话。
最佳答案
make_archive函数采用两个参数:root_dir
和 base_dir
。如果您将 base_dir 设置为其他值,它将删除 ./
前缀。例如:
$ tree
.
├── blah
│ ├── file1
│ └── file2
$ python
>>> import shutil
>>> shutil.make_archive("test", "gztar", ".", "blah")
$ tar -tf test.tar.gz
blah/
blah/file1
blah/file2
这仅限于单个目录。如果您想添加多个这样的目录或文件,则必须使用 tarfile直接模块。
关于python - 命令行 tar 和 Shutil.make_archive 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12307880/