簡體   English   中英

讀取日志文件中的最后一條錯誤消息

[英]Reading last error message in log file

在Python 2.7中,某些循環內有以下代碼

file = open("log.txt", 'a+')
last_position = file.tell()
subprocess.Popen(["os_command_producing_error"], stderr = file)
file.seek(last_position)
error = file.read()
print(error) # example of some action with the error

目的是當file保留整個記錄時,由stderr給出的stderr會得到打印,例如打印出來。

我是Python的初學者,我不清楚stderr = file會發生什么。

我的問題是,即使錯誤不斷記錄在fileerror始終為空。

有人可以解釋為什么嗎?

我嘗試再次添加關閉和打開文件,或者在subprocess行之后添加file.flush() 但是效果還是一樣。

編輯:下面答案中的代碼對我來說很有意義,對於該帖子的作者來說似乎很有用。 對我來說(在Windows中),它不起作用。 它給出一個空的err和一個空的文件log.txt 如果我逐行運行它(例如調試),它確實可以工作。 如何理解和解決這個問題?

編輯:我更改了Popencall ,現在可以使用了。 我想call會等待subprocess完成才能繼續執行腳本。

error為空,因為您在該過程有機會將任何內容寫入文件之前讀取得太早。 Popen()開始一個新過程; 它不等待它完成。

call()等同於Popen().wait() ,它確實等待子進程退出,這就是為什么在這種情況下您應該看到非空error的原因(如果子進程確實向stderr寫入了任何內容)。

#!/usr/bin/env python
import subprocess

with open("log.txt", 'a+') as file:
   subprocess.check_call(["os_command_producing_error"], stderr=file)
   error = file.read()
print(error)

您應該注意混合使用緩沖( .read() )和無緩沖I / O( subprocess .read()

您不需要此處的外部文件即可讀取錯誤:

#!/usr/bin/env python
import subprocess

error = subprocess.check_output(["os_command_producing_error"],
                                stderr=subprocess.STDOUT)
print(error)

它合並stderr和stdout並返回輸出。

如果您不想捕獲stdout,而僅獲取stderr,則可以使用Popen.communicate()

#!/usr/bin/env python
import subprocess

p = subprocess.Popen(["os_command_producing_error"], stderr=subprocess.PIPE)
error = p.communicate()[1]
print(error)

您可以捕獲stderr並將其附加到文件中:

#!/usr/bin/env python
import subprocess

error = bytearray()
p = subprocess.Popen(["os_command_producing_error"],
                     stderr=subprocess.PIPE, bufsize=1)
with p.stderr as pipe, open('log.txt', 'ab') as file:
    for line in iter(pipe.readline, b''):
        error += line
        file.write(line)
p.wait()
print(error)

請參閱Python:從subprocess.communicate()讀取流輸入

請嘗試以下代碼:

file = open("log.txt", 'a+')
sys.stderr = file
last_position = file.tell()
try:
    subprocess.call(["os_command_producing_error"])
except:
    file.close()
    err_file = open("log.txt", 'r')
    err_file.seek(last_position)
    err = err_file.read()
    print err
    err_file.close()

sys.stderr映射標准錯誤消息,例如sys.stdout (映射標准輸出)和sys.stdin (映射標准輸入)。

這會將標准錯誤映射到file 因此,所有標准錯誤都將寫入文件log.txt

暫無
暫無

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

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