簡體   English   中英

如何在仍打印到子進程的控制台的同時將子進程的輸出重定向到文件?

[英]How can I redirect subprocess's output to a file while still printing to the subprocess's console?

我有一個應用程序,在這個應用程序中我運行一個單獨的 Windows 應用程序,它產生自己的終端。 當這個單獨的應用程序運行時,我可以將輸出重定向到一個文件,如下所示

process = subprocess.Popen([self.app, self.app_s],
                           stdout=subprocess.PIPE)

for line in iter(process.stdout.readline, ''):
   print(line)    
   file.write(line)

process.wait()

但是,如果我這樣做,我將無法再打印到子進程的控制台,而只能打印到主應用程序的控制台。

有沒有辦法可以繼續在子進程的控制台中查看輸出,同時將輸出記錄到文件中?

通過以下方式,您可以寫入所有您想要的地方。

process = subprocess.Popen([self.app, self.app_s],
                           stdout=subprocess.PIPE)
    
for line in proc.stdout:
        sys.stdout.write(line)
        file.write(line)

暫無
暫無

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

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