【问题标题】:Unix Popen.communicate not able to gzip large fileUnix Popen.communicate 无法压缩大文件
【发布时间】:2019-09-13 17:37:15
【问题描述】:

我需要在 shell 命令之上使用 python 压缩大小超过 10 GB 的文件,因此决定使用子进程 Popen。

这是我的代码:

outputdir = '/mnt/json/output/'
inp_cmd='gzip -r ' + outputdir

pipe = Popen(["bash"], stdout =PIPE,stdin=PIPE,stderr=PIPE)
cmd = bytes(inp_cmd.encode('utf8'))
stdout_data,stderr_data = pipe.communicate(input=cmd)

它不是对输出目录中的文件进行 gzip 压缩。 有什么办法吗?

【问题讨论】:

    标签: python unix subprocess gzip popen


    【解决方案1】:

    最好的方法是使用 subprocess.call() 而不是 subprocess.communicate()。

    call() 等待命令完全执行,而在 Popen() 中,必须外部使用 wait() 方法才能完成。

    【讨论】:

      【解决方案2】:

      你有没有这样尝试过:

      output_dir = "/mnt/json/output/"
      
      cmd = "gzip -r {}".format(output_dir)
      
      proc = subprocess.Popen(
          cmd,
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE,
          stdin=subprocess.PIPE,
          shell=True,
      )
      
      out, err = proc.communicate()
      

      【讨论】:

      • 我发布的代码和您给出的代码有什么区别?没有明显的变化。
      • 我的回答实际上将命令(cmd)作为第一个参数传递给Popen。它还使用shell=True。您应该阅读Popen 文档并查看security considerations
      • 试过了,不工作。我猜它与等待或超时有关。
      • 您是否收到了TimeoutExpired 异常?如果不是,那可能不是。此代码有效,并将 gzip 目录中的所有文件。你试过在 python shell 中运行它吗?
      • 是的@Alex,我已经运行了它。该命令被执行但没有任何结果。
      猜你喜欢
      • 2018-07-30
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多