私信  •  关注

PM 2Ring

PM 2Ring 最近创建的主题
PM 2Ring 最近回复了
5 年前
回复了 PM 2Ring 创建的主题 » python 3.6 ntp服务器查询功能转换

下面是您的代码的一个版本,它的更改最少,可以在python 3.6上正确运行。除了修复打印和长整型文字(我使用2to3自动修复),我还更改了 NTP_QUERY 到A bytes 字符串。

from contextlib import closing
from socket import socket, AF_INET, SOCK_DGRAM
import sys
import struct
import time

NTP_PACKET_FORMAT = "!12I"
NTP_DELTA = 2208988800 # 1970-01-01 00:00:00
NTP_QUERY = b'\x1b' + bytes(47)

def ntp_time(host="pool.ntp.org", port=123):
    with closing(socket( AF_INET, SOCK_DGRAM)) as s:
        s.sendto(NTP_QUERY, (host, port))
        msg, address = s.recvfrom(1024)
    unpacked = struct.unpack(NTP_PACKET_FORMAT,
            msg[0:struct.calcsize(NTP_PACKET_FORMAT)])
    return unpacked[10] + unpacked[11] / 2**32 - NTP_DELTA

if __name__ == "__main__":
    print(time.ctime(ntp_time()).replace("  "," "))

可以做更多的事情来利用Python3的特性。这里有一个更流线型的版本。我们不需要 contextlib ,因为python 3套接字可以直接在 with 声明。我们不需要 struct ,作为python 3 int 有一个 from_bytes 方法。

from socket import socket, AF_INET, SOCK_DGRAM
import time

NTP_DELTA = 2208988800 # 1970-01-01 00:00:00
NTP_QUERY = b'\x1b' + bytes(47)

def ntp_time(host="pool.ntp.org", port=123):
    with socket( AF_INET, SOCK_DGRAM) as s:
        s.sendto(NTP_QUERY, (host, port))
        msg, _ = s.recvfrom(1024)
    return int.from_bytes(msg[-8:], 'big') / 2 ** 32 - NTP_DELTA

if __name__ == "__main__":
    print(time.ctime(ntp_time()))