栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在python中,如何从c ++共享库捕获标准输出到变量

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在python中,如何从c ++共享库捕获标准输出到变量

Python的

sys.stdout
对象只是位于普通stdout文件描述符之上的Python包装器-
对其进行更改只会影响Python进程,而不会影响基础文件描述符。任何非Python代码,无论是
exec
ed的另一个可执行文件还是已加载的C共享库,都将无法理解,并将继续使用普通的文件描述符进行I
/ O。

因此,为了使共享库输出到其他位置,您需要通过打开一个新的文件描述符,然后使用来替换stdout来更改基础文件描述符

os.dup2()
。您可以使用临时文件作为输出,但是最好使用使用创建的管道
os.pipe()
。但是,如果没有任何内容读取管道,则存在死锁的危险,因此为了防止我们可以使用其他线程排空管道。

以下是一个完整的工作示例,该示例不使用临时文件,并且不容易死锁(在Mac OS X上进行了测试)。

C共享库代码:

// test.c#include <stdio.h>void hello(void){  printf("Hello, world!n");}

编译为:

$ clang test.c -shared -fPIC -o libtest.dylib

Python驱动程序:

import ctypesimport osimport sysimport threadingprint 'Start'liba = ctypes.cdll.LoadLibrary('libtest.dylib')# Create pipe and dup2() the write end of it on top of stdout, saving a copy# of the old stdoutstdout_fileno = sys.stdout.fileno()stdout_save = os.dup(stdout_fileno)stdout_pipe = os.pipe()os.dup2(stdout_pipe[1], stdout_fileno)os.close(stdout_pipe[1])captured_stdout = ''def drain_pipe():    global captured_stdout    while True:        data = os.read(stdout_pipe[0], 1024)        if not data: break        captured_stdout += datat = threading.Thread(target=drain_pipe)t.start()liba.hello()  # Call into the shared library# Close the write end of the pipe to unblock the reader thread and trigger it# to exitos.close(stdout_fileno)t.join()# Clean up the pipe and restore the original stdoutos.close(stdout_pipe[0])os.dup2(stdout_save, stdout_fileno)os.close(stdout_save)print 'Captured stdout:n%s' % captured_stdout


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650761.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号