EDIT: This question is related to this: Python ctypes: how to pass row outputs from a C function into a pandas DataFrame?
My question is how to parse text printed to STDOUT via printf()
into something useable by Python.
I'm working with a Python wrapper in Python3.x around a C library using ctypes. The C library currently does database queries. The function I'm accessing via ctypes is printing the tab-delimited rows of the database via printf()
:
void print_query(const char *input_file,
const char *index, const char *query_string);
whereby input_file
is the path to the file, index
is the index already generated, and query_string
is the string used to query the database.
Here is the Python code I have now:
from ctypes import CDLL
import ctypes
lib = CDLL(".../path/libshared.so")
lib.print_query.restype = ctypes.c_char
lib.print_query.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p)
According to the documentation, https://docs.python.org/3/library/ctypes.html
ctypes.c_char
is a 1-character bytes object. When I try using the function lib.print_query
, the function returns rows via printf()
to STDOUT:
foo = lib.print_query('../file', '.../index', 'January')
outputs
2012 februari 32.610
2012 maart 33.195
2012 april 51.891
and print(foo)
returns b'\x02'
I cannot "access" what has been printed to STDOUT, and I'm not sure how to translate this into a simple string of text. I get the same results trying
foo = io.BytesIO(lib.print_query('../file', '.../index', 'January'))
How can I access this text? It would be useful to stream this into a pandas Dataframe, as it's tab-delimited data.
EDIT: I've tried piping with the following
import subprocess
proc = subprocess.Popen(lib.print_query('../file', '.../index', 'January'), stdout=subprocess.PIPE)
Here's the output:
FileNotFoundError: [Errno 2] No such file or directory: b'\x02': b'\x02'