![](/img/trans.png)
[英]Python: How to change the value of a function inside a class from an outside function
[英]How to print python exception thrown inside exec() function from outside
我正在編寫一個用於執行 python 代碼的小軟件,我想打印異常。 執行以下函數:
def run(self, mode='activate'):
try:
exec(self.mycode)
except Exception:
print(traceback.format_exc())
沒有關於 exec() 函數中將執行什么的信息,它實際上可以是任何 python 代碼。 我想以某種方式打印拋出的異常(由於代碼錯誤,主要是由 python 自動執行的),同時通過 exec() 執行,包括傳遞到 exec() 函數的代碼行,其中拋出了異常。 到目前為止,我只設法將 'exec(mycode)' 作為異常代碼輸出,但我想要在mycode 中崩潰的實際代碼行。
嘗試這個 :
def run(self, mode='activate'):
try:
exec(your_code)
except Exception as e:
print(e)
這行得通!
添加這一行traceback.print_exc()
def run(self, mode='activate'):
try:
exec(your_code)
except Exception as e:
print(e)
traceback.print_exc()
這將為您提供異常信息,並為您提供發生異常/錯誤的行號!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.