[英]Substitution of subprocess.PIPE in Python?
我正在使用子進程模塊與linux命令的輸出進行交互。 下面是我的代碼。
import subprocess
import sys
file_name = 'myfile.txt'
p = subprocess.Popen("grep \"SYSTEM CONTROLLER\" "+ file_name, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
print output.strip()
p = subprocess.Popen("grep \"controller\|worker\" "+ file_name, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
lines = output.rstrip().split("\n")
print lines
我的程序在執行第二個子進程時掛起,即
p = subprocess.Popen("grep \"controller\|worker\""+ file_name,stdout=subprocess.PIPE, shell=True)
我知道進程掛起的原因是緩沖區重定向到subprocess.PIPE正在填充,這阻止了進一步編寫進程。
我想知道是否有任何方法可以避免緩沖區滿的情況,以便我的程序繼續執行而沒有任何掛起問題?
實際問題是模式和文件名之間缺少空格,因此grep
等待標准輸入(stdin)上的輸入。
“緩沖器滿”( .communicate()
是不容易)或p.stdout.read()
它修復沒什么:它加載輸出到存儲器中並且不同於.communicate()
失敗,如果使用多於一個的管)是一紅鯡魚在這里。
Drop shell=True
並使用命令的list參數:
#!/usr/bin/env python
from subprocess import Popen, PIPE
p = Popen(["grep", r"controller\|worker", file_name], stdout=PIPE)
output = p.communicate()[0]
if p.returncode == 0:
print('found')
elif p.returncode == 1:
print('not found')
else:
print('error')
如https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate所述 :
注意:讀取的數據緩沖在內存中,因此如果數據大小很大或不受限制,請不要使用此方法。
而是使用文件對象來讀取生成的文本:
output = p.stdout.read()
只要在您閱讀時沒有其他管道(例如stderr)填滿,就不應阻止該過程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.