原来要添加处理异常机制try...except...else就可以了 |
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老是报错,听说是因为空格的原因。 |