我在 Windows Vista 上运行带有 PyDev 和 Python 3.2 的 Eclipse,并且正在学习有关 Python 和 ctypes 的教程。
但是,我发现当我调用 msvcrt.printf() 来打印一个字符串时,在显示所有其他打印语句之前,它不会显示在 Eclipse 的控制台输出中。
这是我使用的确切代码:
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!?")
这是输出:
23
foo
why!?
Testing: Hello Worlds!
我在别处看到的唯一的解释(对于一般的C)提到了printf是如何缓冲的并且在显示之前需要一个换行符,但是字符串中有一个换行符,我也直接在printf语句中添加了一个('printf ("Testing: %s\n",...') 没有任何区别。
我想在 Eclipse 中工作,我不想每次测试脚本时都必须打开命令提示符,那么有什么方法可以修复控制台输出中的这种顺序吗?为什么会这样?
最佳答案
如果 C 标准库认为 stdout
连接到文件或管道而不是控制台,它将 block 缓冲其输出。您可以通过在 printf
之后发出 fflush
来解决此问题:
msvcrt.fflush(msvcrt.stdout)
您还可以强制 stdout
进入非缓冲模式:
msvcrt.setvbuf(msvcrt.stdout, None, _IONBF, 0)
关于python - Eclipse 和 Python 3 : why does printf() from ctypes display in console output after subsequent print() statements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11653751/