[Python] Why is printf() giving a strange output?

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página