您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从python重定向stdout进行C调用

从python重定向stdout进行C调用

我在下面写了一些附加的注释,这些注释应该更清楚redirect_stdout函数内部的情况:

def redirect_stdout():
    print "Redirecting stdout"
    sys.stdout.flush() # <--- important when redirecting to files

    # Duplicate stdout (file descriptor 1)
    # to a different file descriptor number
    newstdout = os.dup(1)

    # /dev/null is used just to discard what is being printed
    devnull = os.open('/dev/null', os.O_WRONLY)

    # Duplicate the file descriptor for /dev/null
    # and overwrite the value for stdout (file descriptor 1)
    os.dup2(devnull, 1)

    # Close devnull after duplication (no longer needed)
    os.close(devnull)

    # Use the original stdout to still be able
    # to print to stdout within python
    sys.stdout = os.fdopen(newstdout, 'w')

需要注意的重要一件事是,进程在启动时会从OS获取三个不同的文件描述符

评论中所述,上面的代码利用了stdout的文件描述符和文件描述符复制功能来欺骗C代码使用不同的stdout,同时仍保留对python代码中原始stdout的引用。打印。

python 2022/1/1 18:39:09 有328人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶