簡體   English   中英

python 子進程。打開 shell = False,

[英]python subprocess.Popen with shell = False,

此命令運行:

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會導致 memory 泄漏):

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 怎么修?

PS歡迎一般回答。 我有 50 個像上面這樣的奇怪系統調用,我需要重新格式化才能在Shell = False模式下運行。

>是用於 output 重定向的shell 語法 因此,僅當您在 shell 中運行命令時才會對其進行解釋。

如果您需要堅持 gzip 的-c選項,而不是壓縮文件,您可以閱讀 Python 中的 output 並將其寫入文件:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM