[英]python subprocess read stdout as it executes
我在程序中的一個函數檢查哈希文件的md5sum
def check():
print "checking integrity status.."
md5 = subprocess.Popen(["md5sum", "-c", hashfile],shell=False, stdout=subprocess.PIPE)
#fopen = open(basefile, "r")
for f in md5.stdout.readlines():
fc = f.rstrip("\n")
sys.stdout.write("\rChecking..." + fc)
sys.stdout.flush()
現在發生的事情是整個命令首先執行然后使用md5.stdout.readlines從md5進行循環讀取,因此它不是動態的,即我執行命令時不會得到輸出....有沒有辦法我可以在命令執行時獲得輸出...
修復使用glglgl的答案:
def check():
print "checking integrity status.."
md5 = subprocess.Popen(["md5sum", "-c", hashfile],shell=False, stdout=subprocess.PIPE)
#fopen = open(basefile, "r")
fc = "NULL"
i = 0
for f in iter(md5.stdout.readline, ''):
k = fc
fc = f.rstrip("\n")
if "FAILED" in fc:
print fc
i = i + 1
sys.stdout.write("\rChecking... "+ str(i)+ " " + fc + (' ' * (len(k) - len(fc))) )
sys.stdout.flush()
當然。 有幾種方法。
首先,您可以使用md5.stdout.read()
,但是您必須自己進行行分隔。
然后,您可以使用文件對象md5.stdout
作為迭代器進行操作。 但似乎存在緩沖問題,即您沒有立即獲得結果。
然后有可能反復調用md5.stdout.readline()
直到它返回''
。
在這種情況下,第三種方式是首選; 我建議這樣做:
...
for f in iter(md5.stdout.readline, ''):
fc = f.rstrip("\n")
sys.stdout.write("\rChecked " + fc)
sys.stdout.flush()
我也改變了輸出文本,因為只有che檢查已經完成才有輸出。
如果這不是您想要的,而是真正讓每個輸出單獨捕獲,您應該切換到第1點。但這使它更復雜。 我會考慮一個解決方案,表明它是需要的。
在那里,必須考慮以下幾點:
read()
塊,所以應該逐字節讀取(非常難看)。 原始海報是正確的,在2.4版本中不提供hashlib,但md5庫是可用的。 示例解決方法:
try:
# Python 2.5 and up.
import hashlib
md5Hash = hashlib.md5
except ImportError:
# Python 2.4 and below.
import md5
md5Hash = md5.new
somedata = 'foobar'
hashstring = md5Hash (somedata).hexdigest ()
文件大小是多少?
Popen創建一個新的子進程來運行該命令。 也許它在你運行for循環之前完成。
您可以檢查“子進程”是否已完成查看返回碼屬性(在您的代碼中:md5.returncode)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.