gpt4 book ai didi

python - 为什么在不同的 python 版本上运行相同的代码会得到不同的输出?

转载 作者:行者123 更新时间:2023-12-01 00:09:48 25 4
gpt4 key购买 nike

所以当我得到一个意想不到的结果时,我一直在学习 ctypes 库。

我有以下代码只是为了测试 ctypes 是否正常工作:

from ctypes import *
libc = CDLL("libc.so.6")
message_string = "Hello world!\n"
libc.printf("Testing: %s", message_string)

我用python2.7和python3运行它,虽然版本不同,但看起来应该有相同的结果。

root@Crushli-pc ~# python3 --version && python --version
Python 3.7.5
Python 2.7.17
root@Crushli-pc ~# python chapter1-printf.py
Testing: Hello world!
root@Crushli-pc ~# python3 chapter1-printf.py
T⏎ root@Crushli-pc ~#

确实知道 python2 支持已于今年年初结束,这就是为什么我很好奇为什么 python3 不能按预期工作。

我运行代码的机器:

..............                                     root@Crushli-pc 
..,;:ccc,. ---------------
......''';lxO. OS: Kali GNU/Linux Roll
.....''''..........,:ld; Kernel: 5.3.0-kali2-amd
.';;;:::;,,.x, Uptime: 1 hour, 21 mins
..'''. 0Xxoc:,. ... Packages: 2226 (dpkg)
.... ,ONkc;,;cokOdc',. Shell: bash 5.0.11
. OMo ':ddo. Resolution: 1080x1920,
dMc :OO; DE: Xfce
0M. .:o. WM: Xfwm4
;Wd WM Theme: Kali-Dark
;XO, Theme: Kali-Dark [GTK2/
,d0Odlc;,.. Icons: Flat-Remix-Blue-
..',;:cdOOd::,. Terminal: qterminal
.:d;.':;. Terminal Font: Fira Cod
'd, .' CPU: Intel i5-3570 (4)
;l .. GPU: NVIDIA GeForce GTX
.o Memory: 1791MiB / 7922M
c
.'
.


我会提供所需的任何信息,请询问。

我的问题是我做错了什么以及为什么它现在无法正常工作。

编辑:尝试过这个 --> Differences in ctypes between Python 2 and 3 ,并得到这样的代码:

from ctypes import *                                                                                                                                                                                                                   

msvcrt = CDLL("libc.so.6")
message_string = str("Hello world!\n").encode('ascii')
msvcrt.printf("Testing: %s", message_string)

不过,我得到了相同的结果:

root@Crushli-pc ~# cat chapter1-printf.py 
from ctypes import *

msvcrt = CDLL("libc.so.6")
message_string = str("Hello world!\n").encode('ascii')
msvcrt.printf("Testing: %s", message_string)
root@Crushli-pc ~# python3 chapter1-printf.py
T⏎ root@Crushli-pc ~# python chapter1-printf.py
Testing: Hello world!
root@Crushli-pc ~#

最佳答案

由于 printf 需要一个字节字符串,因此您应该在传递字符串之前对其进行编码:

 libc.printf("Testing with non-ascii chars abc€ éю: %s".encode('utf8'),
message_string.encode('utf8'))

输出:

Testing with non-ascii chars abc€ éю: Hello world!

关于python - 为什么在不同的 python 版本上运行相同的代码会得到不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59702469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com