Python版本= 2.7,Windows
您好,
我的Python脚本使用共享C库,我想将脚本的标准IO和共享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()注释掉,则两个字符串都会显示在控制台中。 为什么? 对于Python脚本和使用的共享C库,标准IO是否相同?在这种情况下,如何将两者重定向到同一个文件?
答案 0 :(得分:0)
当我在Linux中运行你的例子时,它运行得很好。
最有可能的是,Windows实际上没有为其stdio
实现使用POSIX文件描述符,因此不会受到更改它们的影响。我不能说我确切知道Windows'libc
实际上是如何实现POSIX文件描述符的,但它可能只是Windows本身使用的POSIX兼容性函数的一些兼容层,以及stdio
代码可能根本不使用它们。
无论如何,在我看来,在stdio
的背后切换文件描述符是一种黑客攻击。我认为你应该使用一个明确的FILE *
变量,你的C函数可以用它来记录,你可以用Python的显式调用来转换。