我注意到,如果我想訪問不存在的JSON文檔中的關鍵字,會突然發生異常。 這個例外的問題是,我沒有在文件中找到很多關於它的問題。 第二個問題是,我沒有找到功能進行檢查,無論項目是否存在。 第三件事是,在這種情況下的例外是沒有必要的。返回NULL會更好。 這是一些示例代碼。是否有人知道一種平抑的方法來抑制拋出異常或忽略它?Python的JSON模塊:通過字典訪問來抑制異常
def make_command(p):
type = p['t']
# remote control is about controlling the model (thrust and attitude)
if type == 'rc':
com = "%d,%d,%d,%d" % (p['r'], p['p'], p['f'], p['y'])
send_command("RC#", com)
# Add a waypoint
if type == 'uav':
com = "%d,%d,%d,%d" % (p['lat_d'], p['lon_d'], p['alt_m'], p['flag_t'])
send_command("UAV#", com)
# PID config is about to change the sensitivity of the model to changes in attitude
if type == 'pid':
com = "%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.2f,%.2f,%.2f" % (
p['p_rkp'], p['p_rki'], p['p_rkd'], p['p_rimax'],
p['r_rkp'], p['r_rki'], p['r_rkd'], p['r_rimax'],
p['y_rkp'], p['y_rki'], p['y_rkd'], p['y_rimax'],
p['t_rkp'], p['t_rki'], p['t_rkd'], p['t_rimax'],
p['a_rkp'], p['a_rki'], p['a_rkd'], p['a_rimax'],
p['p_skp'], p['r_skp'], p['y_skp'], p['t_skp'], p['a_skp'])
send_command("PID#", com)
# This section is about correcting drifts while model is flying (e.g. due to imbalances of the model)
if type == 'cmp':
com = "%.2f,%.2f" % (p['r'], p['p'])
send_command("CMP#", com)
# With this section you may start the calibration of the gyro again
if type == 'gyr':
com = "%d" % (p['cal'])
send_command("GYR#", com)
# User interactant for gyrometer calibration
if type == 'user_interactant':
ser_write("x")
# Ping service for calculating the latency of the connection
if type == 'ping':
com = '{"t":"pong","v":%d}' % (p['v'])
udp_write(com, udp_clients)
能不能請你改一下你的問題,因此讀起來更像是一個實際的問題,而不是像在胡說八道? – 2014-09-21 16:11:29
我不確定你在問什麼,但這可能有所幫助:https://docs.python.org/2/tutorial/errors.html – jonrsharpe 2014-09-21 16:11:59
不要在問題中添加答案。 – jonrsharpe 2014-09-21 17:12:26