簡體   English   中英

subprocess.call沒有等待

[英]subprocess.call is not waiting

with open('pf_d.txt', 'w+') as outputfile:
        rc = subprocess.call([pf, 'disable'], shell=True, stdout=outputfile, stderr=outputfile)
        print outputfile.readlines()

即使文件已寫入某些數據,output.readlines()仍返回[]。 這里不對勁。

看起來subprocess.call()沒有阻塞,並且在read函數之后正在寫入文件。 我該如何解決?

with open('pf_d.txt', 'w+') as outputfile:構造稱為上下文管理器。 在這種情況下,資源是由handle / file對象outputfile表示的文件。 上下文管理器確保在離開上下文時關閉文件。 關閉意味着刷新,然后重新打開文件將向您顯示其所有內容。 因此,解決問題的一種方法是在關閉文件讀取文件:

with open('pf_d.txt', 'w+') as outputfile:
    rc = subprocess.call(...)

with open('pf_d.txt', 'r') as outputfile:
    print outputfile.readlines()

另一種選擇是在刷新並查找后重新使用相同的文件對象:

with open('pf_d.txt', 'w+') as outputfile:
    rc = subprocess.call(...)
    outputfile.flush()
    outputfile.seek(0)
    print outputfile.readlines()

文件句柄始終由文件指針表示,指示文件中的當前位置。 write()將此指針轉發到文件末尾。 seek(0)將其移回開頭,以便隨后的read()從文件的開頭開始。

暫無
暫無

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

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