【发布时间】:2017-04-29 19:55:12
【问题描述】:
我尝试在 Linux 的 python 命令行中使用 C 函数 printf()。为了完成这项工作,我导入了ctypes。我的问题是:如果我创建一个 CDLL 的对象以在循环中使用 printf() 函数,我会得到一个非常奇怪的输出:
>>> 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
>>>
但是,当我在函数内调用此循环时,它按预期工作:
>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6")
>>> def pr():
... for i in range(10):
... libc.printf("%d", i)
... libc.printf("\n")
...
>>> pr()
0123456789
>>>
我无法猜测是什么导致了这种行为...
如果重要的话,我会在 Linux 上使用 Python 2.7.6。
编辑:
Python 版本/操作系统对此没有影响。有关详细信息,请参阅下面的 PM 2Ring 的答案。在 Windows 上,您只需将 libc 的初始化更改为 libc = ctypes.CDLL("msvcrt.dll"),其中 .dll 是可选的。除了调用函数之外,获得正确输出的另一种方法是将printf() 的返回值存储在变量中:
>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6") # "mscvrt.dll" on windows
>>> for i in range(10):
... r = libc.printf("%d", i)
...
0123456789>>>
我还是更喜欢这个函数,因为你可以更轻松地添加结束换行符。
【问题讨论】:
-
实际上抑制输出的更简单方法是在末尾添加一个分号:
libc.printf("%d", i);
标签: python python-2.7 ctypes