pythonpython-2.7printfctypes

Why is printf() giving a strange output?


I tried to use the C-function printf() in the Python command line on Linux. To make that work I imported ctypes. If I create an object of CDLL to use the printf()-function in a loop, I get a really weird output:

>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6")
>>> for i in range(10):
...     libc.printf("%d", i)
...
01
11
21
31
41
51
61
71
81
91
>>>

However when I call this loop inside a function, it works as expected:

>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6")
>>> def pr():
...     for i in range(10):
...         libc.printf("%d", i)
...     libc.printf("\n")
...
>>> pr()
0123456789
>>>

What causes this behavior? I'm using Python 2.7.6 on Linux.


Solution

  • Those extra '1's at the end of each number are the return value from printf, which returns the number of chars that it prints. The return value of a function called in the interactive interpreter is automatically printed (unless it's None).

    In fact, the interactive interpreter prints any non-None expression that isn't assigned. And of course it adds a newline to those expressions, which explains why the output in your first code block is on separate lines.

    Your pr function doesn't have a return statement, so it returns None, and thus no extra stuff gets printed.