Ubuntu c++调用python脚本(Anaconda)

环境配置

  1. 首先创建一个anaconda虚拟环境,环境名字可自己确定,这里使用 call 作为环境名:
$ conda create -n call python==3.8
  1. 安装成功后激活call环境
$ source activate
$ conda activate call

编辑~./bashrc文件,设置使用deeplabv3+_cityscapes环境下的python3.8

alias python='~/anaconda3/envs/call/bin/python3.8'
  1. 更新环境变量
$ source ~/.bashrc
  1. 再次激活 call
conda activate call

代码准备

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(call)

IF(NOT CMAKE_BUILD_TYPE)
  SET(CMAKE_BUILD_TYPE Release)
ENDIF()

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(PYTHON_INCLUDE_DIRS "/home/mirrorubuntu/anaconda3/envs/call/include/python3.8m/")
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_DIRS})
link_directories(/home/mirrorubuntu/anaconda3/envs/call/lib/python3.8/config-3.6m-x86_64-linux-gnu)
set(PYTHON_LIBRARIES "/home/mirrorubuntu/anaconda3/envs/call/lib/libpython3.8m.so")
add_executable(call call.cpp)
target_link_libraries(call ${PYTHON_LIBRARIES})

c++ call.cpp

#include 
#include 
#include 
using namespace std;

int main()
{
 Py_Initialize();
 PyRun_SimpleString("import sys");
 PyRun_SimpleString("import os");
 PyRun_SimpleString("sys.path.append('/home/mirrorubuntu/DeepLabV3Plus-Pytorch')");
 PyRun_SimpleString("print(sys.path)");
 PyErr_Print();
 PyObject *pName = NULL;
 PyObject *pModule = NULL;
 PyObject *pFunc = NULL;
 pName= PyUnicode_FromString("predict");//载入python脚本
 pModule = PyImport_Import(pName);
 if (pModule == NULL){
	cout << "don't find the python file!" << endl;
 }
 pFunc = PyObject_GetAttrString(pModule, "main");
 PyEval_CallObject(pFunc, NULL);      //调用函数
 Py_Finalize();
 return 0;
}

https://blog.csdn.net/u012149181/article/details/122385679
https://blog.csdn.net/xranmail/article/details/84759553?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-5.pc_relevant_antiscanv2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-5.pc_relevant_antiscanv2&utm_relevant_index=8
https://www.cnblogs.com/jikexianfeng/p/9173403.html
https://blog.csdn.net/qq_42688495/article/details/120563844
https://blog.csdn.net/Carry_all/article/details/103207949

你可能感兴趣的:(ubuntu,python,ubuntu,c++,python)