Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a function from python file by Boost.Python

I am totally new to boost.python. I reviewed a lot of recommending of using boost.python to apply with python, however still not easy to understand and find a solution for me.

What I want is to import a function or class that directly from a python "SourceFile"

Example File: Main.cpp MyPythonClass.py

Let's says if there is a "Dog" class in "MyPythonClass.py" with "bark()" function, how do I get callback and send argument in cpp?

I have no idea what I should do! Please help me!

like image 799
陽品駒 Avatar asked Jul 27 '16 18:07

陽品駒


People also ask

How do you import a function in Python?

Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.

How do I import a .PY file into Python?

You need to tell python to first import that module in your code so that you can use it. If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory.

How do I import Python from terminal?

Start a fresh command-line Python interpreter in the same directory as your module file. Starting the intepreter in the same directory is the simplest way to be sure that your module will be found by the import statement. Evalute the dir function to see what is in the initial global namespace. Import your module.

How to import a function from a file in Python?

The process of importing a function from a file in Python is similar to importing modules. You have to create two files. Next, insert the definition of the function in one file and call the function from another. Name the new file myfile.py and insert a function.

What is the difference between a Python import and load module?

The Python import makes external functions and classes available to a program. The syntax is like x = zyx….. This Python source file can have a class (for objects) or functions in the file. It can import other files. This is a compiled Python file (from abc.py). The load module is generated from C source.

What is the import path in Python?

Recall the import path you saw earlier. It essentially tells Python where to search for modules. However, if Python finds a module in the module cache, then it won’t bother searching the import path for the module. In object-oriented programming, a singleton is a class with at most one instance.

What are imports in Python and why are they important?

Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable. This tutorial will provide a thorough overview of Python’s import statement and how it works.


1 Answers

When one needs to call Python from C++, and C++ owns the main function, then one must embed the Python interrupter within the C++ program. The Boost.Python API is not a complete wrapper around the Python/C API, so one may find the need to directly invoke parts of the Python/C API. Nevertheless, Boost.Python's API can make interoperability easier. Consider reading the official Boost.Python embedding tutorial for more information.


Here is a basic skeleton for a C++ program that embeds Python:

int main()
{
  // Initialize Python.
  Py_Initialize();

  namespace python = boost::python;
  try
  {
    ... Boost.Python calls ...
  }
  catch (const python::error_already_set&)
  {
    PyErr_Print();
    return 1;
  }

  // Do not call Py_Finalize() with Boost.Python.
}

When embedding Python, it may be necessary to augment the module search path via PYTHONPATH so that modules can be imported from custom locations.

// Allow Python to load modules from the current directory.
setenv("PYTHONPATH", ".", 1);
// Initialize Python.
Py_Initialize();

Often times, the Boost.Python API provides a way to write C++ code in a Python-ish manner. The following example demonstrates embedding a Python interpreter in C++, and having C++ import a MyPythonClass Python module from disk, instantiate an instance of MyPythonClass.Dog, and then invoking bark() on the Dog instance:

#include <boost/python.hpp>
#include <cstdlib> // setenv

int main()
{
  // Allow Python to load modules from the current directory.
  setenv("PYTHONPATH", ".", 1);
  // Initialize Python.
  Py_Initialize();

  namespace python = boost::python;
  try
  {
    // >>> import MyPythonClass
    python::object my_python_class_module = python::import("MyPythonClass");

    // >>> dog = MyPythonClass.Dog()
    python::object dog = my_python_class_module.attr("Dog")();

    // >>> dog.bark("woof");
    dog.attr("bark")("woof");
  }
  catch (const python::error_already_set&)
  {
    PyErr_Print();
    return 1;
  }

  // Do not call Py_Finalize() with Boost.Python.
}

Given a MyPythonClass module that contains:

class Dog():
    def bark(self, message):
        print "The dog barks: {}".format(message)

The above program outputs:

The dog barks: woof
like image 153
Tanner Sansbury Avatar answered Oct 18 '22 00:10

Tanner Sansbury