【问题标题】:python subprocess.Popen with shell = False,python subprocess.Popen with shell = False,
【发布时间】:2020-01-22 14:44:16
【问题描述】:

这个命令运行:

process_1     =  subprocess.Popen("gzip -dc " + infile + " > " + inter_file, 
                                  cwd                = base_dir,
                                  stdout             = subprocess.PIPE, 
                                  shell              = True,
                                  universal_newlines = True)
output, error = process_1.communicate()  

现在,我想删除shell=True(我有很多类似上面的行和 我怀疑Shell = True 会导致内存泄漏):

process_1     =  subprocess.Popen(["gzip", "-dc", infile, ">", inter_file], 
                                  cwd                = base_dir,
                                  stdout             = subprocess.PIPE, 
                                  shell              = False,
                                  universal_newlines = True)
output, error = process_1.communicate() 

产量:

gzip:  > .gz: No such file or directory

gzip: blabla.txt: not in gzip format

blabla.txtinter_file:似乎设置Shell = False 混淆了infileinter_file。如何解决?

附:欢迎提供一般性答案。我有 50 个类似上述的系统调用,需要重新格式化才能在 Shell = False 模式下运行。

【问题讨论】:

    标签: python unix subprocess


    【解决方案1】:

    > 是用于输出重定向的shell syntax。因此,只有当您在 shell 中运行命令时才会对其进行解释。

    如果您需要坚持使用 gzip 的 -c 选项,而不是压缩文件,您可以在 Python 中读取输出并将其写入文件:

    process_1     =  subprocess.Popen(["gzip", "-dc", infile], 
                                      cwd                = base_dir,
                                      stdout             = subprocess.PIPE, 
                                      shell              = False,
                                      universal_newlines = True)
    output, error = process_1.communicate() 
    
    with open(inter_file, 'wb') as file_desc:
        file_desc.write(output)
    

    如果您确定您有足够的磁盘空间将原始文件在磁盘上保存两次,至少暂时,您可以先复制文件,然后在不使用-c 的情况下运行gzip

    from shutil import copyfile
    
    copyfile(infile, inter_file)
    process_1     =  subprocess.Popen(["gzip", "-d", inter_file], 
                                      cwd                = base_dir,
                                      stdout             = subprocess.PIPE, 
                                      shell              = False,
                                      universal_newlines = True)
    

    【讨论】:

    • 谢谢。但我不想在 python 中读取文件。我只想执行命令。 Shell = False 有没有办法做到这一点?
    • 不,没有办法,因为gzip 不支持指定除原始 input.file.gz 之外的输出文件。您使用 gzip -c 禁用了此功能
    • PS:我添加了一种在压缩之前复制文件的方法。这不需要在 Python 中读取文件,但在磁盘利用率方面效率较低。
    • 复制文件当然也需要时间。我会以此为基准。如果在 Python 中编写文件很慢,我会感到惊讶。 (请注意,您已经使用 communicate() 阅读过它)
    • 是的,当然,因为在该示例中需要输出。但请不要随心所欲地进行性能优化,衡量吧!
    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 2012-12-29
    • 2014-01-15
    • 2019-05-20
    • 2015-07-19
    相关资源
    最近更新 更多