2

In Jupyter Notebook when i try to print "hello world!" via ctypes.cdll.msvcrt.printf function it turns length of the string. I am just trying to learn ctypes , and i wondered why does it happened ? Because if i try to execute that code in terminal it works well . And how can i use that function in Jupyter Notebook ? The code is below.

import ctypes

ctypes.cdll.msvcrt.printf(b"Hello World")

Jupyter Notebook Cell output :

11

Normal Execution output :

Hello World

Wasp Nesser
  • 197
  • 1
  • 1
  • 9

1 Answers1

2

IPython is not a real terminal.

What IPython (the core in the Jupyter Notebook) does is capturing the stdout, stderr and other buffers before the data get printed out to the real terminal. That's happening on the Python level.

However ctypes does not print on the Python level with your code, it uses a function that's capable to print data. That function is present in a shared library in the system and is able to print on the C level (or better said via using a low-level print function from kernel mostly).

Regarding the 11 value, that might be the length of the result you get from the printf() function as you said i.e. len("Hello World") without the ending \0 character, however it might even be the real output of the object that's supposed to represent the data printed out via ctypes.cdll.msvcrt.printf(). If the latter is the case, IPython properly captured the output, but ctypes just stored it in a different place (if at all).

I'm not on Windows, so can't say what's the result, but try to store it in a variable and then attempt to get its properties from which you might be able to retrieve the output and plug it back into the stdout for IPython:

out = ctypes.cdll.msvcrt.printf(b"Hello World")
dir(out)       # methods, properties, etc
vars(out)      # the whole dictionary structure (might fail)
out.__slots__  # __slots__ attribute in case __dict__ for vars() is not present

You can check capture_output() here.

You might want to redirect out output from ctypes to a file or to a buffer you'd read from afterwards.

Peter Badida
  • 7,432
  • 8
  • 33
  • 74