Dylan.Ruby
Dylan.Ruby

Reputation: 13

How to call a Python function from C++ on Ubuntu 20.04

I'm currently in a class where I'm asked to establish integration between Python and C++ as we will be working with both later in the class. My instructor has provided some simple C++ and Python code so we can test the integration and has also provided instructions on how to set this up using Visual Studio. I currently only have access to Ubuntu and my (very old) laptop won't be able to handle a VM.

I'm currently using Clion as my IDE and Anaconda as a virtual environment. I've spent most of the day trying to figure this out and I believe the issue is related to my CMake file as I know pretty much nothing about CMake right now, but plan to learn it soon.

The CMakeLists.txt, main.cpp, and myPython.py are all in the main project directory.

CMakeLists.txt

cmake_minimum_required(VERSION 3.21)
project(myProject)

set(CMAKE_CXX_STANDARD 14)

add_executable(myProject main.cpp)

target_include_directories(myProject PUBLIC /usr/include/python3.9)
target_link_directories(myProject PUBLIC /usr/lib/python3.9)
target_link_libraries(myProject PUBLIC python3.9)

For CMakeLists.txt I also tried the following but got the same error/output regardless of which one I used

cmake_minimum_required(VERSION 3.21)
project(myProject)

set(CMAKE_CXX_STANDARD 14)

find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
add_executable(myProject main.cpp)
target_link_libraries(myProject PUBLIC Python3::Python)

main.cpp

#include <python3.9/Python.h>
#include <iostream>
#include <string>


using namespace std;

// the main in the provided code is void but Clion gave me an error saying to change it to int
int main()
{
    cout << "Start 1 \n";
    Py_Initialize();
    cout << "2\n";
    PyObject* my_module = PyImport_ImportModule("myPython");
    cerr << my_module << "\n";
    PyErr_Print();
    cout << "3\n";
    PyObject* my_function = PyObject_GetAttrString(my_module,
                                                   "printsomething");
    cout << "4\n";
    PyObject* my_result = PyObject_CallObject(my_function, NULL);
    Py_Finalize();
    return 0;
}

myPython.py

import re
import string


def printsomething():
    print("Hello from Python!")

The expected output is

Start 1
2
01592AE0 // this will vary since it's the .py files location
3
4
Hello from Python!

what I'm getting when I run it is

Start 1
2
0 // output is red
3
ModuleNotFoundError: No module named 'myPython' // output is red

Since I'm not familiar with CMake and would consider myself a "general user" when it comes to Ubuntu, I may need some additional details on any steps provided.

Upvotes: 1

Views: 899

Answers (1)

David
David

Reputation: 467

Add this in your main function after Py_Initialize();

PySys_SetPath(L".:/usr/lib/python3.8");

this is the search path for python module. Add . to search in the current path.

Upvotes: 2

Related Questions