【问题标题】:Store output of gunzip/tar -t in Python在 Python 中存储 gunzip/tar -t 的输出
【发布时间】:2021-07-06 15:09:42
【问题描述】:

我尝试在 Python 中存储命令的输出:gunzip -t / tar -t,但我不知道如何。确实,在 shell termianl 中,我可以使用 echo $?但在 Python 中,使用 os.popen() 或 os.system() 是不可能的。

我当前的脚本如下:

os.system("gunzip -t Path_to_tar.gz")
gzip_corrupt = os.popen("echo $?").read().replace('\n','')
os.system("gunzip -c Path_to_tar.gz | tar -t > /dev/null")
tar_corrup = os.popen("echo $?").read().replace('\n','')
print(tar_corrup)
print(gzip_corrupt)

您知道如何在 python 中存储 gunzip -t 的输出吗?

【问题讨论】:

标签: python os.system


【解决方案1】:

我不是 python wiz,但我想说你需要将 os.system 的输出更改为:

os.system("gunzip -c Path_to_tar.gz | tar -t > /dev/null")

类似于:

os.system("gunzip -c Path_to_tar.gz | tar -t > /tmp/myfile.out")

然后,转身,打开 /tmp/myfile.out,然后将其读回,等等。(我建议生成一个唯一的名称以避免多次运行会发生冲突并导致错误 - 还包括日期/保持单独运行的时间戳 - 单独)

这一行: tar_corrup = os.popen("echo $?").read().replace('\n','')

只会为您提供 gunzip 命令的退出代码 - 而不是 gunzip 本身的输出(请参阅“echo $? 做什么?”1。)

这是一种“蛮力”方法 - 但易于阅读和稍后编辑,应该可以工作。

【讨论】:

  • 谢谢,但我已经尝试将结果存储在临时文件中,但它不起作用,因为这些命令是特定的^^。我读到我们需要运行 $?在它知道 tar.gz 被行号损坏之后 --> 0 没关系,更不行
  • @AlexandreSolane 你错了。 $? 在 Python shell 中不起作用。使用无效命令的简单测试将显示这一点。检查运行os.popen 的退出代码的正确方法在文档中进行了说明:docs.python.org/3/library/subprocess.html。您也不应该将os.popenos.system 混用。如果必须,请使用popen
【解决方案2】:

这是我的问题的解决方案,我在不同的 tar 文件上对其进行了测试,它看起来可以工作:

# On check si la backup est corrompue
gzip_corrupt = False
tar_corrup = False

if const.weekday < 6:
    incr_backup.incremental_backup()
else:
    full_backup.full_backup()

# On vérifie l'intégrité du gzip
if os.system("gunzip -t " + const.target_directory + const.backup_file_name):
    gzip_corrupt = True

# On vérifie l'intégrité du tar
if os.system("gunzip -c " + const.target_directory + const.backup_file_name + " | tar -t"):
    tar_corrup = True

# Si la backup est corrompue --> on envoie un mail à la BAL PIC
if gzip_corrupt or tar_corrup:
    mail_notice.send_email()

所以,显然。 os.system() 知道是 tar -t 还是 gunzip -t 输出一些东西,我用 if 块进行测试。

如果 os.system("tar -t ...") return something ,则表示 tar 已损坏或不是 tar 文件,因此我的布尔值取 True 当 tar 正常时,os.system() 不返回任何内容 --> 被 Python 读取为 False

我希望它能在 python 中的这个特定命令上帮助其他人

谢谢大家的帮助

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 2011-08-07
    • 1970-01-01
    • 2022-10-17
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多