关于ntplib时间同步的问题。

我想做个用python实现ntp时间同步的小程序,要求定时发出时间同步的命令,代码如下。
import os
import time
import ntplib
count=0
while count==0:
  c = ntplib.NTPClient()
  response = c.request('pool.ntp.org')
  ts = response.tx_time
  _date = time.strftime('%Y-%m-%d',time.localtime(ts))
  _time = time.strftime('%X',time.localtime(ts))
  os.system('date {} && time {}'.format(_date,_time))
  print("start:%s"%time.ctime())
  time.sleep(20)
  print("end:%s"%time.ctime())

网络正常时,时间同步正常,一没有网络,就立马发出异常。
Traceback (most recent call last):
  File "D:/py/synctime.py", line 8, in <module>
    response = c.request('pool.ntp.org')
  File "C:\Python33\lib\site-packages\ntplib.py", line 287, in request
    addrinfo = socket.getaddrinfo(host, port)[0]
socket.gaierror: [Errno 11004] getaddrinfo failed
然后退出。不能一直在while中循环,这是怎么回事,有什么解决办法。


请先 登录 后评论

5 个回答

安诺斯诺
原来要添加处理异常机制try...except...else就可以了
请先 登录 后评论
黄文庆
谁知道ntplib.NTPException是什么异常。
请先 登录 后评论
Bertha02
import os
import time
import ntplib
import socket
import subprocess
count=0
while count==0:
try:
   c = ntplib.NTPClient()
   response = c.request('pool.ntp.org')
except socket.gaierror:
   time.sleep(5)
   print("网络不通\n")
   continue
except ntplib.NTPException:
   time.sleep(5)
   print("请求NTP时间同步超时\n")
   continue
else:
   ts = response.tx_time
   _date = time.strftime('%Y-%m-%d',time.localtime(ts))
   _time = time.strftime('%X',time.localtime(ts))
   print("date "+_date)
   ps=subprocess.Popen(["date ",_date],shell=True)
   ps.wait()
   pw=subprocess.Popen(["time ",_time],shell=True)
   pw.wait()
  # os.system("date "+_date)
  # os.system('date {} && time {}'.format(_date,_time))
   print("时间已同步,同步时间为:%s"%time.ctime())
   time.sleep(30)


##重新写了,去掉os.system,使用subprocess.Popen,因为在python2.5下面,os.system老是报错,听说是因为空格的原因。
请先 登录 后评论
ztruth
今天用python2.5来测试,同步不了时间,用python3.3可以用,就不知道是哪里出错误。python2.5中也没有报错,就是时间没有同步。
请先 登录 后评论
乔衣
python2.5是在win98系统下测试的,而python3.3是在win7下测试的。
请先 登录 后评论
  • 5 关注
  • 0 收藏,416 浏览
  • Gui銘 提出于 2021-08-07 15:47

相似问题