Python版本=2.7,Windows
你好,
我的Python脚本使用一个共享C库,我想在一个文件中重定向脚本的标准IOs和共享C库,如下例所示(仅限于stderr流)
C共享库代码:

#include <stdio.h>

void my_print(void)
{
    fprintf(stderr, "This string isn't displayed\n");
}

Python脚本:
import os, sys, ctypes

def test():
    parserDll = ctypes.CDLL("./titi.dll")           # my shared C library
    file_stderr_fds = os.open("./toto.txt", 777)    # file in which redirect the stderr
    saved_stderr_fds = os.dup(2)                    # Backup stderr
    os.dup2(file_stderr_fds, 2)                     # Redirect stderr to file
    print >> sys.stderr, "zozo"                     # Python test redirect for Python script --> Ok
    parserDll.my_print(None)                        # test for the shared C library --> KO

if __name__ == "__main__":
    test()

当我运行这个Python脚本时,在toto.txt文件中,我读取了“zozo”(从Python脚本中显示),但没有从共享C库中读取任何内容。但是,如果我注释os.dup2()out,这两个字符串都将显示在控制台中。
为什么?
Python脚本和使用的共享C库的标准IOs不一样吗?在这种情况下,如何将两者重定向到同一个文件?

最佳答案

当我在Linux中运行您的示例时,它工作得很好。
最有可能的是,Windows的stdio实现实际上并不使用POSIX文件描述符,因此不受您更改它们的影响。我不能说我确切地知道Windows'libc是如何实现POSIX文件描述符的,但它可能只是POSIX兼容函数的某个兼容层,在Windows本机使用的任何函数之上,stdio代码可能根本不使用它们。
无论如何,在我看来,在stdio后面切换文件描述符有点麻烦。我认为您可能应该使用一个显式的FILE *变量,您的C函数可以使用它来记录日志,您可以使用Python的显式调用来切换它。

关于python - 将导入的C DLL的stderr重定向到任意文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14007262/

10-12 18:04
查看更多