gpt4 book ai didi

Python import_array 使得无法使用 ctrl-c 杀死嵌入式 python

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:56 28 4
gpt4 key购买 nike

我正在尝试在嵌入式 Python 中使用 Numpy。我在 Boost 1.57 中使用 Python 3.4 和 boost::python。为了防止 Python 设置一个信号处理程序来阻止我使用 Ctrl+C 终止我的程序,我使用 Py_InitializeEx(0)。

现在的问题是,当我调用 import_array() 来设置 Numpy 时,这似乎添加了信号处理程序,我无法再使用 Ctrl+C 终止程序。

这是示例程序:

#include <boost/python.hpp>

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#define PY_ARRAY_UNIQUE_SYMBOL damaris_ARRAY_API
#include <numpy/arrayobject.h>

using namespace boost::python;

static void* init_numpy() {
import_array();
return NULL;
}

int main( int argc, char ** argv ) {
try {
Py_InitializeEx(0);

object main_module((
handle<>(borrowed(PyImport_AddModule("__main__")))));

object main_namespace = main_module.attr("__dict__");

init_numpy();

handle<> ignored(( PyRun_String( "print(\"Hello, World\")",
Py_file_input,
main_namespace.ptr(),
main_namespace.ptr() ) ));
while(1) {
sleep(1);
}
} catch( error_already_set ) {
PyErr_Print();
}
}

在 main 中注释“init_numpy”行时,我可以使用 Ctrl+C 终止程序。如何在仍然使用 Numpy 的同时使信号不被 Python 捕获?

最佳答案

经过一些研究回答我自己的问题,我不知道这是否是最干净的方法,但这种方法有效:

不仅仅是

import_array();

使用

PyOS_sighandler_t sighandler = PyOS_getsig(SIGINT);
import_array();
PyOS_setsig(SIGINT,sighandler);

这基本上存储了调用 import_array 之前存在的信号处理程序,然后我们执行了一个与信号处理程序混淆的 import_array,因此我们在之后立即使用 PyOS_setsig 恢复存储的信号处理程序。

关于Python import_array 使得无法使用 ctrl-c 杀死嵌入式 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28750774/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com