为什么我在调用 C 函数写入日志时收到错误的文件描述符错误?

Why am I getting a bad file descriptor error while calling a C function to write to log?

此函数调用 C 函数从 Python 写入日志。它确实打印日志文本,但在它之后抛出错误。我做错了什么?

def py_log_callback(msg, level):
    if not string_at(msg):
        return
    msg = "Log entry: {}".format(string_at(msg).decode())
    print(msg)

log_callback = CFUNCTYPE(None, c_char_p, c_int)(py_log_callback)
lib = CDLL(libpath)
lib.Foo(log_callback, DEBUG_LEVEL)

输出:

Log entry: <log text here>

Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 234, in 'calling callback function'
  File "test.py", line 36, in py_log_callback
    print(msg)
OSError: [Errno 9] Bad file descriptor

我刚刚将输出保存到文本文件,问题已解决。

sys.stdout = open('stdout.txt', 'w')