Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse and Python 3: why does printf() from ctypes display in console output after subsequent print() statements

I am running Eclipse with PyDev and Python 3.2 on Windows Vista, and was working through a tutorial on Python and ctypes.

However, I found that when I call msvcrt.printf() to print a string, this is not displayed in the console output for Eclipse until all other print statements have displayed.

Here is the exact code I use:

from ctypes import *

msvcrt = cdll.msvcrt
message_string = "Hello Worlds!\n"

printf = msvcrt.printf
print(printf("Testing: %s".encode('ascii'),message_string.encode('ascii')))


print("foo")

print("why!?")

and here is the output:

23
foo
why!?
Testing: Hello Worlds!

The only explanations I have seen elsewhere (for C in general) mention how printf is buffered and needs a newline before displaying, but there is a newline in the string, and I also added one directly to the printf statement ('printf("Testing: %s\n",...') and it made no difference.

I want to work in Eclipse, I don't want to have to keep opening a command prompt every time i want to test scripts, so is there any way I can fix this ordering in the console output? And why does this happen?

like image 860
Brian Avatar asked Nov 14 '22 01:11

Brian


1 Answers

If the C standard library thinks stdout is connected to a file or a pipe rather than a console, it will block-buffer its output. You can work around this by issuing a fflush after printf:

msvcrt.fflush(msvcrt.stdout)

You may also be able to force stdout into non-buffered mode:

msvcrt.setvbuf(msvcrt.stdout, None, _IONBF, 0)
like image 59
ecatmur Avatar answered Feb 07 '23 04:02

ecatmur