Ubuntu c++调用python脚本传递参数(Anaconda)

由于需要在c++程序中跑python程序进行语义分割,需要在c++程序中传递参数给Python程序

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,*pModule,*pDict,*pFunc,*pArgs;
 pName= PyUnicode_FromString("call_modify");//载入python脚本
 pModule = PyImport_Import(pName);
 if (pModule == NULL){
	cout << "don't find the python file!" << endl;
 }
 pDict = PyModule_GetDict(pModule);
 pFunc = PyDict_GetItemString(pDict, "main");
 pArgs = PyTuple_New(1);
 PyTuple_SetItem(pArgs, 0, Py_BuildValue("s","000000"));//picture name
 // 调用Python函数
 PyObject_CallObject(pFunc, pArgs);
 Py_Finalize();
 return 0;
} 

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.8/")
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_DIRS})
link_directories(/home/mirrorubuntu/anaconda3/envs/call/lib/python3.8/config-3.8m-x86_64-linux-gnu)
set(PYTHON_LIBRARIES "/home/mirrorubuntu/anaconda3/envs/call/lib/libpython3.8.so")
add_executable(call call.cpp)
target_link_libraries(call ${PYTHON_LIBRARIES})

python call_modify.py

import os

def main(s):
    path = "python /home/mirrorubuntu/DeepLabV3Plus-Pytorch/predict.py --input /home/mirrorubuntu/Kitti/data_odometry_color/07/image_2/" + s + ".png --dataset cityscapes --model deeplabv3plus_mobilenet --ckpt /home/mirrorubuntu/DeepLabV3Plus-Pytorch/weights/best_deeplabv3plus_mobilenet_cityscapes_os16.pth --save_val_results_to /home/mirrorubuntu/DeepLabV3Plus-Pytorch/test_results"
    os.system(path)

构建虚拟环境,执行
在这里插入图片描述

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