Alexandru Ghiulea
Alexandru Ghiulea

Reputation: 11

Linking the output of a Python script to the input of a C++ program

My python script is outputting the values of an analogue to digital converter to the console of a Raspberry Pi. In order to manipulate this data, I need to send this output to the input of a C++ file. Should I wrap my python code as C++ and include it inside of the program, or is there an easier way of passing the data directly?

Upvotes: 1

Views: 1576

Answers (3)

darune
darune

Reputation: 11145

If you mean at runtime, probably the simpelst way is via a std::system call

From https://en.cppreference.com/w/cpp/utility/program/system:

#include <cstdlib>
#include <fstream>
#include <iostream>

int main()
{
    std::system("ls -l >test.txt"); // execute the UNIX command "ls -l >test.txt"
    std::cout << std::ifstream("test.txt").rdbuf();
}

Possible output:

total 16
-rwxr-xr-x 1 2001 2000 8859 Sep 30 20:52 a.out
-rw-rw-rw- 1 2001 2000  161 Sep 30 20:52 main.cpp
-rw-r--r-- 1 2001 2000    0 Sep 30 20:52 test.txt

And just run your python whatever instead.

Upvotes: 0

Banneisen
Banneisen

Reputation: 33

To pass such a small amount of data I would recommend using the bash pipe. It seems to be the easiest way.

python script.py | ./cpp_prog

Upvotes: 2

skratchi.at
skratchi.at

Reputation: 1151

My fist thought on this would be to embed your script into a C++ program. Python itself suggests this. This would be the cleanest way. So you can control, if and when you get new data from your ADC.

Short excerpt from the link:

The simplest form of embedding Python is the use of the very high level interface. This interface is intended to execute a Python script without needing to interact with the application directly. This can for example be used to perform some operation on a file.

#include <Python.h>

int
main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}

The Py_SetProgramName() function should be called before Py_Initialize() to inform the interpreter about paths to Python run-time libraries. Next, the Python interpreter is initialized with Py_Initialize(), followed by the execution of a hard-coded Python script that prints the date and time. Afterwards, the Py_Finalize() call shuts the interpreter down, followed by the end of the program. In a real program, you may want to get the Python script from another source, perhaps a text-editor routine, a file, or a database. Getting the Python code from a file can better be done by using the PyRun_SimpleFile() function, which saves you the trouble of allocating memory space and loading the file contents.

And so on and so forth. This will guide you in your way. May your project be good =)

Upvotes: 0

Related Questions