我正在编写一个用于执行Python代码的小软件,我想打印异常。执行以下函数:
def run(self, mode='activate'):
try:
exec(self.mycode)
except Exception:
print(traceback.format_exc())
没有关于 exec() 函数中到底执行什么的信息,它实际上可以是任何 python 代码。我想在通过 exec() 执行时以某种方式打印抛出的异常(主要是由于代码错误而由 python 自动生成),包括传递到抛出异常的 exec() 函数的代码行。 到目前为止,我只设法将“exec(mycode)”作为异常代码输出,但我想要在mycode中崩溃的实际代码行。
最佳答案
试试这个:
def run(self, mode='activate'):
try:
exec(your_code)
except Exception as e:
print(e)
这会起作用!
关于python - 如何从外部打印 exec() 函数内部抛出的 python 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59201472/