Python3.6以上版本调用Py_Finalize()后出现段错误的技术问询
问题:Ubuntu 18.04下C++嵌入高版本Python调用Azure App Insights重复初始化/终止崩溃问题
当前环境为Ubuntu 18.04 LTS,通过C++嵌入Python实现日志上传至Azure Application Insights。代码在Python3.6版本下运行正常,但该版本已停止官方维护。升级至更高版本Python后,重复调用Py_Initialize()和Py_Finalize()会触发段错误;若仅调用一次Py_Finalize()则不会崩溃,但日志无法上传至云端,且需保持应用持续运行。
安装Python与App Insight依赖
sudo apt-get updatesudo apt install python3.6(或更高版本)python3 -V(用于检查Python3版本)sudo apt-get install python3-devsudo apt-get install libpython3.6-dev(需对应安装的Python版本调整,如Python3.8则改为libpython3.8-dev)sudo apt-get install python3-pipsudo apt install rustcsudo -H pip3 install setuptools_rustsudo -H pip3 install opencensus-ext-azure applicationinsights
代码示例
#include <stdio.h> #include <Python.h> #include <iostream> #include <string> #include <stdint.h> void CallAppInsightUploadFunction(); int main() { for (int i = 0; i <= 5; i++) { Py_Initialize(); CallAppInsightUploadFunction(); std::cout << "Loop count: " + std::to_string(i) << std::endl; Py_Finalize(); } printf("\nGood Bye...\n"); return 0; } void CallAppInsightUploadFunction() { PyRun_SimpleString("import sys"); PyRun_SimpleString("if not hasattr(sys, 'argv'): sys.argv = ['']"); PyRun_SimpleString("import logging"); PyRun_SimpleString("from opencensus.ext.azure.log_exporter import AzureLogHandler"); PyRun_SimpleString("logger = logging.getLogger(__name__)"); PyRun_SimpleString("logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey=<YOUR-INSTRUMENTATION-KEY>'))"); PyRun_SimpleString("logger.setLevel(logging.INFO)"); PyRun_SimpleString("logger.info('Testing AppInsight Uploads from VM...')"); }
CMakeLists.txt文件
cmake_minimum_required(VERSION 3.13) project(AppInsightTest) find_package(PythonLibs 3 REQUIRED) include_directories(include) include_directories(${PYTHON_INCLUDE_DIRS}) message("Python Include directory:") message("${PYTHON_INCLUDE_DIRS}") message("Python Library:") message("${PYTHON_LIBRARIES}") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) include_directories(${CMAKE_SOURCE_DIR}/include) file(GLOB SOURCES src/*.cpp) add_executable(AppInsightTest ${SOURCES}) target_link_libraries(AppInsightTest PRIVATE ${PYTHON_LIBRARIES} )
Python3.6下的运行输出
Loop count: 0 context.c:55: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time Loop count: 1 context.c:55: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time Loop count: 2 context.c:55: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time Loop count: 3 context.c:55: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time Loop count: 4 context.c:55: warning: mpd_setminalloc: ignoring request to set MPD_MINALLOC a second time Loop count: 5 Good Bye...
预期输出
使用Python3.6以上版本运行相同代码时,应得到与上述一致的输出。使用Python3.8等更高版本时,需在cmake命令中添加以下参数:-DPYTHON_LIBRARY=/usr/lib/aarch64-linux-gnu/libpython3.8.so -DPYTHON_INCLUDE_DIR=/usr/include/python3.8
内容的提问来源于stack exchange,提问作者Gaurang
相关产品推荐
相关产品推荐

