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