Passing a list through Python to C++ - python

So I have a Python program that's finding .txt file directories and then passing those directories as a list(I believe) to my C++ program. The problem I am having is that I am not sure how to pass the list to C++ properly. I have used :
subprocess.call(["path for C++ executable"] + file_list)
where file_list is the [] of txt file directories.
My arguments that my C++ code accepts are:
int main (int argc, string argv[])
Is this correct or should I be using a vector? When I do use this as my argument and try to print out the list I get the directory of my executable, the list, and then smiley faces, symbols, and then the program crashes.
Any suggestions? My main point that I am trying to find out is the proper syntax of utilizing subprocess.call. Any help would be appreciated! thanks!

Another option is to use cython, (not a direct answer). Here is a simple complete example:
Suppose you have the following files:
cython_file.cpp
python_file.py
setup.py
sum_my_vector.cpp
sum_my_vector.h
setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension(
name="cython_file",
sources=["cython_file.pyx", "sum_my_vector.cpp"],
extra_compile_args=["-std=c++11"],
language="c++",
)]
setup(
name = 'cython_file',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
)
cython_file.pyx
from libcpp.vector cimport vector
cdef extern from "sum_my_vector.h":
int sum_my_vector(vector[int] my_vector)
def sum_my_vector_cpp(my_list):
cdef vector[int] my_vector = my_list
return sum_my_vector(my_vector)
sum_my_vector.cpp
#include <iostream>
#include <vector>
#include "sum_my_vector.h"
using namespace::std;
int sum_my_vector(vector<int> my_vector)
{
int my_sum = 0;
for (auto iv = my_vector.begin(); iv != my_vector.end(); iv++)
my_sum += *iv;
return my_sum;
}
sum_my_vector.h
#ifndef SUM_MY_VECTOR
#define SUM_MY_VECTOR
using namespace::std;
int sum_my_vector(vector<int> my_vector);
#endif
python_file.py
from cython_file import sum_my_vector_cpp
print sum_my_vector_cpp([1,2,3,5])
Now run
python setup.py build_ext --inplace
and the you can run the python file
python python_file.py
11

"Passing a list through Python to C++"
An alternative approach would be to use Boost.Python, this may not answer your question directly, but still its worth pointing out another solution.
#include <boost/python.hpp>
#include <vector>
#include <string>
void get_dir_list( boost::python::list dir_list )
{
for (int i = 0; i < len(dir_list); ++i)
{
std::string x = boost::python::extract<std::string>(dir_list[i]);
// perform stuffs
std::cout << "This is " << x << std::endl ;
}
}
BOOST_PYTHON_MODULE(get_dir_list)
{
def("get_dir_list", get_dir_list);
}
Compiled Using :
g++ main.cpp -shared -fPIC -o get_dir_list.so -I/usr/include/python2.7 -lboost_python
Usage :
import get_dir_list
import os
get_dir_list.get_dir_list(os.listdir('.'))
Live Demo Here

I'll post this alternative solution since it would also work for other long lists of strings that needed to be passed.
In your Python script create a text file (I'll call it "masterFile") and write the file paths to the masterFile. You could give each file path a separate line. Then pass the masterFile's file path to your C++ program. This way you don't have to worry about the length of your command line arguments. Let your C++ program open and read the file for processing.
You can use something like os.remove() to get rid of the masterFile in your Python script once the C++ program has finished.
Also, you mentioned in the comments that you need to do different tasks dependent on different file paths: A suggestion would be to add a char at the beginning of each line in the masterFile to signal what needs to be done for the particular file. Example:
a Random/path/aFile.txt # a could mean do task 1
b Random2/path2/differentFile.c # b could mean do task 2

You pass a list to subprocess.call. subprocess.call converts this to what is needed for the system (which may vary, but certainly isn't a Python list). The system then arranges for this to be copied somewhere in the new process, and sets up the standard arguments to main, which are int, char**. In your C++ program, you must define main as int main( int argc, char** argv ); nothing else will work. (At least... a system could support int main( std::string const& ) or some such as an extension. But I've never heard of one that did.)

Related

Using pybind11 within C++ in JUCE Framework

I'm trying to read a string list output from a Python script, in order to pass it to a JUCE MainComponent (written in C++).
The code is the following (which is a starting one, just to test the pybind library):
#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
namespace py = pybind11;
MainComponent::MainComponent()
{
auto math = py::module::import("math");
auto resultobj = math.attr("sqrt")(2);
double result = resultobj.cast<double>();
}
However, I always encounter the following error:
_PyRuntime.gc.**generation0** was nullptr.
Any suggestions? Thanks in advance
You have to first initialize the Python interpreter, like this:
MainComponent::MainComponent()
{
py::scoped_interpreter guard{};
auto math = py::module::import("math");
auto resultobj = math.attr("sqrt")(2);
double result = resultobj.cast<double>();
}
You also have to link with the needed python libraries. In CMake, this means adding
target_link_libraries(your_target PRIVATE pybind11::embed)
to your CMakeLists.txt file.

Call function from python in C++

I'm currently working on a project with a separate cli and gui. The gui part is written in C++ to keep the exectuable small. I compiled my python program with pyinstaller and need to call some functions from the C++ program.
Python part:
import configparser
def getconfig() -> list:
config = configparser.ConfigParser()
config.read("config.ini")
section1 = config["general"]
section2 = section["section2"]
return [section1, section2] #should be a list of dict?
Compiling it via pyinstaller --onefile --clean myprogram.py
What i would like to do in C++ is :
//please correct me if this is the wrong type,
//i know i probably need to do a bit of parsing between python and C++ types
std::vector<std::unordered_map<std::string, std::string>> > = myprogram.getconfig()
I just don't want to do the config parsing in C++ again, or would you recommend this as it's probably easier to call the compiled python binary?
This program just needs to run on linux, windows is not necessary.
If you are only planning to run on POSIX-compatible systems (ie. GNU/Linux), you could spawn a new process to run the Python script, e.g. using the C function exec. Example:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main()
{
char* args[] = { "pythonscript.py", NULL };
int t = execv("pythonscript.py", args);
if(t < 0) printf("%s\n", strerror(errno));
return 0;
}
And then in pythonscript.py:
#!/usr/bin/python3
print("hello, world!")
This trick works with bash scripts as well.
The script must be executable though, so remember to run chmod +x pythonscript.py.
EDIT:
You will likely need to use pipes or other mechanisms for inter-process communication. (this is not my expertise!)

Unable to import Python module written in C

I have been trying to work out how to make a .pyd (Python Extension Module) file from a C script (without swig or anything else except MinGW) and have successfully built it into a .pyd.
The problem however occurs when I try and import the module.
If I run it the module runs successfully (as far as I can see) and then an error appears saying Python Has Stopped Working and it closes without executing the rest of the program.
Here is my C script (test.c):
#include <python.h>
int main()
{
PyInit_test();
return 0;
}
int PyInit_test()
{
printf("hello world");
}
And Python Script (file.py):
import test
print('Run From Python Extension')
I compiled the script with:
gcc -c file.py
gcc -shared -o test.pyd test.c
I can't find any errors when compiling in command prompt and am using python 3.6 (running on Windows 10).
I can't find much on the subject and would prefer to keep away from Cython (I already know C) and Swig.
Any help to tell me what is wrong would be fantastic.
Creating a Python extension is completely different than writing regular C code. What you have done is simply creating a valid C program but that doesn't make sense for Python.
That's how your program should look like (it's just a skeleton, not the proper, working code):
#include <Python.h>
#include <stdlib.h>
static PyObject* test(PyObject* self, PyObject* args)
{
printf("hello world");
return NULL;
}
static PyMethodDef test_methods[] = {
{"test", test, METH_VARARGS, "My test method."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC init_test_methods() {
Py_InitModule("test", test_methods);
}
int main(int argc, char** argv)
{
/* Pass argv[0] to the Python interpreter */
Py_SetProgramName(argv[0]);
/* Initialize the Python interpreter. Required. */
Py_Initialize();
/* Add a static module */
init_test_methods();
}
I recommend you read more about this at the following link: http://dan.iel.fm/posts/python-c-extensions/ as well as in the official docs.

Using cython cdef public variable in c++ : variable is never initialized

I'm trying to translate some simple cython to c++ :
cdef public int G = 1
and then use it in my c++ code :
#include <Python.h>
#include "test.h" // The file generated by the cython command
#include <iostream>
int main(int argc, char **argv) {
std::cout << "G : " << G << std::endl;
}
Output is :
G : 0
I've looked into the test.cpp cython-generated file, and on line 897, I have
G = 1;
So why is G evaluated to 0 in the main ?
Here are the commands used to compile :
cython.exe test.pyx -3 --cplus
g++ test.cpp test_main.cpp -IC:\Python36-32\include -LC:\Python36-32\libs -lpython36
What you generate when you use cython is a python extension module. You cannot link it directly into an executable, as it needs to be dynamically imported and linked to libpython. In that process, your extension's initialization function is run, which will cause your G to be set to 1.
So you should:
Build a python extension from your cython (using -shared and outputting a DLL).
Load python interpreter in your main. In your program, you don't even initialize python at the moment.
Import it in your main using PyImport_ImportModule("mymodule").
Untested, but your main should look like this:
#include <Python.h>
int main(int argc, char * argv[])
{
Py_Initialize();
PyObject * test_module = PyImport_ImportModule("test");
// do something with test_module
Py_Finalize();
return 0;
}
You can get G from python using PyObject_GetAttrString(), or since you declared it as cdef, you can access it directly using your OS's symbol resolution tools, such as GetProcAddress() for windows.
It may be possible to link dynamically at load time, yet still use importmodule to let python do its initialization magic, but I have no idea how to do that or if it's even possible.

Cpp compilation from python fail but not in the shell

I have a cpp file that compiles fine with g++ by using the shell:
extern "C"{
#include <quadmath.h>
}
inline char* print( const __float128& val)
{
char* buffer = new char[128];
quadmath_snprintf(buffer,128,"%+.34Qe", val);
return buffer;
}
int main(){
__float128 a = 1.0;
print(a);
return 0;
}
However, when I try to compile it via a python scrit, it fails with the following error:
"undefined reference to quadmath_snprintf"
Here the code of the python script:
import commands
import string
import os
(status, output) = commands.getstatusoutput("(g++ test/*.c -O3 -lquadmath -m64)")
Any idea how to solve this? Thanks.
When you open a shell a whole of stuff is silently initialized for you, and most important for your issue, environment variables are set. What you most likely miss is the definition of LIBRARY_PATH, which is the variable used by the linker to look for libraries matching the ones you instruct it to link using the -lNAME flags.
What the linker needs is a list of directories where it will search for files matching libNAME.{a,so}. You can also pass these directories directly using the -L flag, but in general, you should probably try to use a program like CMake, Make or any other build tool.
This will give you access to commands like find_package and target_link_libraries (CMake), to find, respectively add libraries to your build targets, instead of having to maintain your python to compile your stuff.

Categories

Resources