[英]Python - Execute Process -> Block till it exits & Suppress Output
我正在使用以下內容執行進程並從Python隱藏其輸出。 它在循環中,我需要一種方法來阻止,直到子進程終止,然后才轉到下一次迭代。
subprocess.Popen(["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
使用subprocess.call()
。 來自文檔:
subprocess.call(* popenargs,** kwargs)
使用參數運行命令。 等待命令完成,然后返回returncode屬性。 參數與Popen構造函數相同。
編輯:
subprocess.call()
使用wait()
,而wait()
容易受到死鎖(正如Tommy Herbert指出的那樣)。 來自文檔:
警告:如果子進程生成足夠的輸出到stdout或stderr管道,這會阻塞等待OS管道緩沖區接受更多數據,這將導致死鎖。 使用communic()來避免這種情況。
因此,如果您的命令生成大量輸出,請使用communicate()
代替:
p = subprocess.Popen(
["scanx", "--udp", host],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
如果你根本不需要輸出,你可以將devnull傳遞給stdout
和stderr
。 我不知道這是否有所作為,但通過bufsize。 使用devnull現在subprocess.call
不吃虧的僵局了
import os
import subprocess
null = open(os.devnull, 'w')
subprocess.call(['ls', '-lR'], bufsize=4096, stdout=null, stderr=null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.