V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
XIVN1987
V2EX  ›  Jupyter

jupyter 中通过 ctypes 调用 printf()时,不显示 printf()打印内容

  •  
  •   XIVN1987 · 2020-12-31 17:56:21 +08:00 · 1421 次点击
    这是一个创建于 1183 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码:

    from ctypes import *
    
    libc = cdll.LoadLibrary('msvcrt.dll')
    libc.printf(c_char_p(b'Hello %d %.2f\n'), c_int(16), c_double(2.3))
    

    在标准交互环境中显示内容为:

    Hello 16 2.30
    14
    

    在 ipython 中,显示内容为:

    Hello 16 2.30
    Out[31]: 14
    

    在 jupyter 中,显示内容为:

    Out[15]: 14
    

    请问在 jupyter 中如何显示“Hello 16 2.30”

    2 条回复    2021-01-01 09:57:53 +08:00
    XIVN1987
        1
    XIVN1987  
    OP
       2021-01-01 09:42:14 +08:00
    找到一篇文章,上面说出现这种问题的原因是:
    IPython forwards the Python-level sys.stdout and sys.stderr, but it leaves the process-level file descriptors that C code will write to untouched. That means that in a context like this notebook, these functions will print to the terminal, because they are not captured.

    文章链接: https://notebook.community/minrk/wurlitzer/Demo
    XIVN1987
        2
    XIVN1987  
    OP
       2021-01-01 09:57:53 +08:00
    虽然在 jupyter notebook 中没有显示“Hello 16 2.30”,但在 jupyter.exe 终端中有显示,,能够验证代码的执行效果,,所以这个问题不算很严重
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4701 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:47 · PVG 17:47 · LAX 02:47 · JFK 05:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.