I have code that uses ctypes to try to determine if the file that sys.stdout stdout points to is sys.stdout . I know that on any POSIX-compatible system and even on Windows, it should be safe to assume that this is true if sys.stdout.fileno() == 1 , so my question is not how to do it in general.
In my code (which already uses ctypes for something not related to my question), I casually had something like:
libc = ctypes.CDLL(ctypes.util.find_library('c')) real_stdout = libc.fileno(ctypes.c_void_p.in_dll(libc, 'stdout')) if sys.stdout.fileno() == real_stdout: ...
This works fine on Linux, so I havenβt thought much about it. It looked better and readable than hard coding 1 as a file descriptor. But after a few days, I found that my code did not work on OSX.
It turns out that OSX libc does not export a single character called 'stdout'. Instead, stdio.h has stdout, defined as:
#define stdout __stdoutp
If I change my code to c_void_p.in_dll(libc, '__stdoutp') , my code works as expected, but, of course, only OSX. Windows, it turns out, has a similar problem (at least when using MSVC).
I will probably just change my code to use 1 , but my question still stands out of curiosity if there is a cross-platform way to get the stdio pointer (as well as stdin and stderr ) without assuming it uses a POSIX compatible descriptor ?
source share