I tried to use the C-function printf()
in the python command line on Linux. To make that work, I imported ctypes
. My problem is: 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
>>>
I can't guess what causes this behavior ...
I'm using Python 2.7.6 on Linux if it matters.
EDIT:
Python version / operating system has no influence to this. See PM 2Ring's answer below for details. On Windows you only have to change the initialization of libc
to libc = ctypes.CDLL("msvcrt.dll")
where .dll
is optional. Another way to get the correct output than calling a function would be storing the return value of printf()
in a variable:
>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6") # "mscvrt.dll" on windows
>>> for i in range(10):
... r = libc.printf("%d", i)
...
0123456789>>>
I still prefer the function because you can add a concluding linebreak easier.