V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
XIVN1987
V2EX  ›  Jupyter

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

  •  
  •   XIVN1987 · Dec 31, 2020 · 2469 views
    This topic created in 1943 days ago, the information mentioned may be changed or developed.

    代码:

    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 replies    2021-01-01 09:57:53 +08:00
    XIVN1987
        1
    XIVN1987  
    OP
       Jan 1, 2021
    找到一篇文章,上面说出现这种问题的原因是:
    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
       Jan 1, 2021
    虽然在 jupyter notebook 中没有显示“Hello 16 2.30”,但在 jupyter.exe 终端中有显示,,能够验证代码的执行效果,,所以这个问题不算很严重
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3386 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:23 · PVG 20:23 · LAX 05:23 · JFK 08:23
    ♥ Do have faith in what you're doing.