我正在编写一个用于执行 python 代码的小软件,我想打印异常。执行以下函数:
def run(self, mode='activate'):
try:
exec(self.mycode)
except Exception:
print(traceback.format_exc())
Run Code Online (Sandbox Code Playgroud)
没有关于 exec() 函数中到底执行什么的信息,它实际上可以是任何 python 代码。我想在通过 exec() 执行时以某种方式打印抛出的异常(主要是由于代码错误而由 python 自动生成),包括传递到抛出异常的 exec() 函数的代码行。到目前为止,我只设法将 'exec(mycode)' 作为异常代码输出,但我想要在mycode中崩溃的实际代码行。
我写了以下小脚本:
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
enum class Day {sunday, monday, thuesday, wednesday, thursday, friday, saturday};
Day unusedDay, today = sunday;
}
Run Code Online (Sandbox Code Playgroud)
但我有一个问题.当我调试程序时,编译器说:
error: 'sunday' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
但有我的枚举课.为什么周日没有申报?我怎么能改变呢?
谢谢你回答:)