簡體   English   中英

如何在 python 中捕獲不是異常的錯誤消息?

[英]How to capture error message in python that is not an exception?

我正在使用一個名為 pywaves 的模塊與waves.exchange API 進行交互。 問題是有時當我嘗試下訂單時,它會被拒絕並顯示錯誤消息:

[ERROR] Order Rejected...

問題是如何在我的腳本中捕獲此錯誤消息。 生成錯誤的代碼是: myOrder = myAddress.sell(assetPair = PRO_WAVES, amount = 1491999999, price = proprice1, matcherFee = 700000, maxLifetime = 3600)該錯誤不會引發異常,也不會被捕獲到myOrder中。 如何將此錯誤中的數據獲取到變量中以便我可以使用它?

庫內部的錯誤可能是寫入標准錯誤 output sys.stderr 因此,您可以重定向錯誤 output 並檢查庫是否正在寫入它。 例如,請參閱有關記錄錯誤 output 的這個問題

一旦你有了一個記錄器(或者在你的情況下是一個記錄和解析任何錯誤的 class),像這樣使用它:

import sys
_stderr = sys.stderr
sys.stderr = MyErrorCheckLogger()
try:
    myOrder = myAddress.sell(...)
finally:
    sys.stderr = _stderr

當然,您可以對sys.stdout執行相同的操作 — 標准 output 通道。


編輯:這是一個完整的示例,我們捕獲直接打印到標准 output ( stdout ) 的任何錯誤消息。

import sys

class ErrorChecker:
    def __init__(self, output):
        self.output = output               # Save the original `stdout` (or `stderr`)
        self.buffer = ""                   # The buffer for the message printed

    def write(self, message):
        self.buffer += message             # Add any message to our buffer
        self.output.write(message)         # Print it as original intended

    def flush(self):
        self.output.flush()

def throwError(f, *args, **kwargs):
    sys.stdout = ErrorChecker(sys.stdout)  # Create a new output-stream with buffer
    try:
        result = f(*args, **kwargs)        # Execute the code that might cause an error
    finally:
        buffer = sys.stdout.buffer         # Get the output buffer
        sys.stdout = sys.stdout.output     # Restore the original 'stdout'
    if buffer.startswith("[ERROR]"):       # If the output is an error message, raise
        raise Exception(buffer)            # it as an actual exception
    return result

myOrder = throwError(myAddress.sell, assetPair = PRO_WAVES, amount = 1491999999, price = proprice1, matcherFee = 700000, maxLifetime = 3600)

閱讀實際代碼后,您 似乎可以使用pywaves.setThrowOnError()在記錄錯誤時引發異常,例如 在您描述的情況下 但是,無論出於何種原因似乎沒有記錄在案,因此使用風險自負。 您可以使用問題跟蹤系統與開發人員就此進行溝通。

暫無
暫無

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

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