gpt4 book ai didi

linux - 如何将 "tar"shell 命令翻译成 Python

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:06 27 4
gpt4 key购买 nike

我是编程新手,我的任务是将 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)

关于linux - 如何将 "tar"shell 命令翻译成 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49074208/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com