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

2020-12-31 17:56:21 +08:00
 XIVN1987

代码:

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”

1465 次点击
所在节点    Jupyter
2 条回复
XIVN1987
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
2021-01-01 09:57:53 +08:00
虽然在 jupyter notebook 中没有显示“Hello 16 2.30”,但在 jupyter.exe 终端中有显示,,能够验证代码的执行效果,,所以这个问题不算很严重

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/740728

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX