Python 3.5 ctypes libc printf() 只打印字符串的第一个字节 Windows 7/10

Python 3.5 ctypes libc printf() only prints first byte of string Windows 7/10

我正在尝试遵循 Gray Hat Python 示例之一,它在 Python 2.7 中运行良好,但在 Python 3.5 中结果被截断。

from ctypes import * 

msvcrt = cdll.msvcrt
message_string = "Hello World!\n"
msvcrt.printf("Testing: %s\n", message_string)

你可以看到上面代码的输出只是字母 T.

基于一些与此类似的其他帖子,在最后一行添加 b 会有所帮助,但 message_string 会被截断。

from ctypes import * 

msvcrt = cdll.msvcrt
message_string = "Hello World!\n"
msvcrt.printf(b"Testing: %s\n", message_string)

如何在 Windows 7 或 10 上使用 Python 3.5 打印存储在 message_string 变量中的整个字符串?

命令应该是 msvcrt.printf("Testing: %s\n" % message_string) - 你用逗号代替 % 符号

成功了!也需要在变量声明中添加 b 。这么小的细节也...请参阅下面调整后的代码:

from ctypes import * 

msvcrt = CDLL('msvcrt')
message_string = b"Hello World!\n"
msvcrt.printf(b"Testing: %s\n", message_string)

在 Windows 7 64 位,w/ Python 3.5 和 Windows 10 64 位 w/ Python 3.4

上测试

灰帽 Python - 第 1 章-printf.py - 示例