繁体   English   中英

如何将“ tar” shell命令转换为Python

[英]How do I translate the “tar” shell commands into Python

我是编程的新手,我已经获得了将Shell命令转换为python的任务,作为一种自动化过程的方法。 以下是命令:

$ cd /users/me/repos/
$ mv -i file file-1.0.0
$ tar cfz file-1.0.0.tgz file-1.0.0
$ mv -i file-1.0.0 file
$ tar xfz file-1.0.0.tgz

除了tar命令,我知道该怎么做。 我不确定它们做什么以及如何在Python中实现它们。

这将在路径“ tar_path”中获取目录“ tar_file”,并创建一个名为“ tar_file_file.tgz”的压缩版本。 然后将内容解压缩到目录“ hello”中

import os
import tarfile
from contextlib import closing

fun = "/users/me/temp/fun/"
tar_path = "{0}tar_file".format(fun)
hello = '{0}hello'.format(fun)

def makedir(dir_path):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

makedir(fun)
os.chdir(fun)
makedir(hello)

    #create tgz, enable gzip, create archive file
def make_tarfile(output_filename, source_dir):
    with closing(tarfile.open(output_filename, "w:gz")) as tar:
        tar.add(source_dir, arcname = os.path.basename(source_dir))
    tar.close()

    #extract, unpack in gzip format, read archived content
def extract_tarfile(output_filename, source_dir):
    t = tarfile.open(output_filename, "r:gz")
    t.extractall(source_dir)


make_tarfile('tar_file_file.tgz', tar_path)
extract_tarfile('tar_file_file.tgz', hello)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM