簡體   English   中英

子進程 PIPE 標准輸出到兩個不同的進程

[英]Subprocess PIPE stdout to two different processes

我正在嘗試將subprocess進程stdout重定向到兩個不同的進程。 對一個進行處理可以正常工作,但不能完全使用兩個不同的過程

代碼:

def terminate_processes(*args):
    try:
        for i in reversed(args):
            try:
                i.terminate()
            except:
                pass
    except:
        pass

def main(x='192.168.0.2'):


    # system('sudo nmap -O '+x+'|grep "Running: " > os_detect.txt')
    # system('cat os_detect.txt|cut -d " " -f2 > os.txt')
    # system('cat os_detect.txt|cut -d " " -f3 > os_version.txt')
    
    p1 = subprocess.Popen(['sudo', 'nmap', '-O', str(x)], stdout=subprocess.PIPE)
    
    p2 = subprocess.Popen(['grep', 'Running: '],  stdin=p1.stdout, stdout=subprocess.PIPE)
    
    p3 = subprocess.Popen(['cut', '-d', ' ', '-f2'],  stdin=p2.stdout,
                                                    stdout=subprocess.PIPE, 
                                                    stderr=subprocess.STDOUT,
                                                    universal_newlines=True)
    
    p4 = subprocess.Popen(['cut', '-d', ' ', '-f3'],  stdin=p2.stdout,
                                                    stdout=subprocess.PIPE, 
                                                    stderr=subprocess.STDOUT,
                                                    universal_newlines=True)

    while p3.poll() is None:
        for line in p3.stdout.readlines():
            if line.strip():
                print(line.strip())

    while p4.poll() is None:
        for line in p4.stdout.readlines():
            if line.strip():
                print(line.strip())

    terminate_processes(p1,p2,p3,p4)

正如我所說,理論上應該起作用,因為僅使用p3而不是p4時起作用,但在這種情況下不起作用可能是因為stdout被鎖定。

任何指導將不勝感激。

我正在反轉終止 function 內的args數組,導致在殺死父進程之前殺死子進程。

.read()通常的工作方式,在我知道的大多數情況下,為了第二次使用它,你必須使用.seek()將讀取頭倒回到以前的位置.

看:

您可以做的是使用communicate並手動傳入標准輸出數據(讀取一次,傳入兩者):

out, err = p2.communicate() # out is None, since you don't 

p2_output = ''.join(list(out))

p3 = Popen([...], stdin=PIPE, ...)
p4 = Popen([...], stdin=PIPE, ...)

stdout_data3, err = p3.communicate(input=p2_output)
stdout_data4, err = p4.communicate(input=p2_output)

另請注意,與您目前擁有的相比,這可能會改變需要進行輪詢的方式。

有關的:

暫無
暫無

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

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