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

蓝咒 提交于 2019-12-10 14:53:08

问题


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?


回答1:


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)



回答2:


Although this does not answer your question but printf is returning 23 which is the number of printed characters, you could replace it with sprintf and that will return the string and will be displayed in the console in the right expected order.

However, I don't see a reason for using mscvcrt's printf when you can do the same with python.



来源:https://stackoverflow.com/questions/11653751/eclipse-and-python-3-why-does-printf-from-ctypes-display-in-console-output-af

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!