python - C++调用Python如何处理SystemExit异常

标签 python c++ exception interface python-embedding

我有一个C++代码,它使用PyRun_SimpleFileEx C API执行Python脚本。
py文件看起来像这样

import time

time.sleep(2)
raise SystemExit("Sorry, it is time to exit.")
SystemExit是通过调用python诸如quit()abort()之类的东西而引发的
由于SystemExit继承自BaseException而不是Exception,因此无法捕获并关闭Python环境以及C++应用程序。
有什么办法可以从C++捕获上述异常?
提前致谢
祝一切顺利
兆字节

最佳答案

您可以创建一个wrapper.py并从中运行代码。

class ExceptionWrapper(Exception):
    def __init__(self, exc):
        self.exc = exc

def run_code(filename):
    try:
        exec(open(filename).read(), globals=globals(), locals=locals())
    except BaseException as ex:
        raise ExceptionWrapper(ex)
从C++使用此包装器:
#include <Python.h>

int main() {
    Py_Initialize();
    PyObject * wrapper = PyImport_ImportModule("wrapper");
    if (!wrapper) {
        PyErr_Print();
        exit(1);
    }
    PyObject * res = PyObject_CallMethod(wrapper, "run_code", "s", "simple.py");
    if (!res) {
        PyErr_Print();
        // PyObject *type, *value, *traceback;
        // PyErr_Fetch(&type, &value, &traceback);
        // PyErr_NormalizeException(&type, &value, &traceback);
        // or handle exception manually here
        // PyErr_Restore(type, value, traceback);
    }
    Py_XDECREF(res);
    printf("exit from C\n");
}
请注意,这只是一个POC,运行任意代码并不安全。
您可以修改包装器以接受文件描述符作为参数。

关于python - C++调用Python如何处理SystemExit异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63813775/

相关文章:

python - 如何在 Django 中设置 id 标签等于 URL 名称

python - FFT:查找并消除信号中的噪声 50Hz

c++ - 通过基指针将派生类转换为基之一

java - 是否应该在 throws 子句中声明 IllegalArgumentException?

Python "While"循环和中断它们

python - 如何从容器中删除相同的对象(但不一定是相同的对象)?

c# - 在 wcf 服务中引用 c++ 库

c++ - 二维数组在退出循环后移除其元素

java - Hibernate 嵌套延迟加载和 LazyInitializationException

exception - Jython:测试以防止异常 "Cannot create PyString with non-byte value"?