小编Aem*_*myl的帖子

为什么printf()在python中给出一个奇怪的输出?

我试图printf()在Linux上的python命令行中使用C函数.为了完成这项工作,我导入了ctypes.我的问题是:如果我创建一个在循环中CDLL使用printf()-function 的对象,我得到一个非常奇怪的输出:

>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)

但是,当我在函数内部调用此循环时,它按预期工作:

>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6")
>>> def pr():
...     for i in range(10):
...         libc.printf("%d", i)
...     libc.printf("\n")
...
>>> pr()
0123456789
>>>
Run Code Online (Sandbox Code Playgroud)

我猜不出是什么导致了这种行为......
如果重要的话,我在Linux上使用Python 2.7.6.

编辑:

Python版本/操作系统对此没有影响.有关详细信息,请参阅下面的PM 2Ring的答案.在Windows上,您只需将初始化更改libclibc = ctypes.CDLL("msvcrt.dll")where .dll是可选的.获取正确输出比调用函数的另一种方法是将printf()变量值存储在变量中:

>>> …
Run Code Online (Sandbox Code Playgroud)

python ctypes python-2.7

38
推荐指数
2
解决办法
4292
查看次数

标签 统计

ctypes ×1

python ×1

python-2.7 ×1