如何避免KeyError

时间:2019-07-09 19:32:28

标签: python-3.x udp

我写了一个python脚本,我确定此代码已经起作用。

但是现在当我执行它时,我得到了一个KeyError。

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import socket
import sys
import time
from time import sleep

bufsize = 8192  # 8 kByte

receive = ("", 8020 )
send = ("10.10.11.2", 8021 )

UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDPSock.bind(receive)

print( "UDPServer Waiting for client on port", receive )

def Ausgang1on():

    UDPSock.sendto(b"Ausgang1 on", send)
    print( "Ausgang1 on"    )

def Ausgang1off():
    UDPSock.sendto(b"Ausgang1 off", send)
    print( "Ausgang1 off"   )

options = {     "Ausgang1on"  :  Ausgang1on,
                "Ausgang1off" : Ausgang1on,
}


while True:
    try:
        dataFromClient, addr = UDPSock.recvfrom(bufsize)
        options[dataFromClient]()
        print( dataFromClient)
        print( options)  
    except KeyError:
        print( dataFromClient)
        print( "KeyError")
        UDPSock.sendto(b"KeyError", send)

pi@door:~/skripte $ sudo python3 tets1.py
UDPServer Waiting for client on port ('', 8020)
b'Ausgang1on'
KeyError

我也发送了正确的值,也执行def Ausgang1on():,但总是收到KeyError

我做错了什么?

问候

0 个答案:

没有答案