编辑:此问题与此相关:Python ctypes: how to pass row outputs from a C function into a pandas DataFrame?
我的问题是如何将通过printf()
打印到STDOUT的文本解析成Python可用的东西。
我正在使用ctypes在C ++库中使用Python3.x中的Python包装器。 C库当前进行数据库查询。我通过ctypes访问的函数是通过printf()
打印数据库分隔的行:
void print_query(const char *input_file,
const char *index, const char *query_string);
其中input_file
是文件的路径,index
是已生成的索引,query_string
是用于查询数据库的字符串。
这是我现在拥有的Python代码:
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)
根据文件https://docs.python.org/3/library/ctypes.html
ctypes.c_char
是一个1个字符的字节对象。当我尝试使用函数lib.print_query
时,该函数通过printf()
将行返回到STDOUT:
foo = lib.print_query('../file', '.../index', 'January')
输出
2012 februari 32.610
2012 maart 33.195
2012 april 51.891
和print(foo)
返回b'\x02'
我无法“访问”打印到STDOUT的内容,我不知道如何将其转换为简单的文本字符串。我尝试了相同的结果
foo = io.BytesIO(lib.print_query('../file', '.../index', 'January'))
如何访问此文本?将它传输到pandas Dataframe中会很有用,因为它是制表符分隔的数据。
编辑:我尝试使用以下
进行管道传输import subprocess
proc = subprocess.Popen(lib.print_query('../file', '.../index', 'January'), stdout=subprocess.PIPE)
这是输出:
FileNotFoundError: [Errno 2] No such file or directory: b'\x02': b'\x02'