Python Forum
Sockets and Sendmail - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Networking (https://python-forum.io/forum-12.html)
+--- Thread: Sockets and Sendmail (/thread-20725.html)



Sockets and Sendmail - taintedsushi - Aug-27-2019

I have a socket client program that resends any received data to other connected clients.

I just added a function to send an email when certain data is received. I pass the data to the sendemail function and the email is sent.

However, when the program returns from the sendemail routine, I end up with a KeyError. If I comment out the actual sendmail() command, no KeyError is produced.

I can't figure out how these two things are related or what to do to fix it.

This all seems to work fine:

try:
  data = s.recv(64)
except socket.error, ex:
  print ex
if data:

# A readable client socket has data
    print '> ', data
    message_queues[s].put(data)

# Add output channel for response

if s not in outputs:
    outputs.append(s)
    update_html(data)
    checknewtrack(data)
    if (newtrack):
        sendemail()
But after coming back from the sendemail() function, it chokes on this code :

for s in writeable:
try:
    next_msg = message_queues[s].get_nowait() <---- KEYERROR HERE
except Queue.Empty:
    outputs.remove(s)
else:
    for t in connected_clients:
        t.send(next_msg)
Error:
Traceback (most recent call last): File "/home/user/bin/lora-gateway.py", line 192, in <module> do_work( True) File "/home/user/bin/lora-gateway.py", line 135, in do_work next_msg = message_queues[s].get_nowait() KeyError: <socket._socketobject object at 0x7f43a6617c20>
Any help would be appreciated.


RE: Sockets and Sendmail - taintedsushi - Aug-28-2019

I get the feeling that since I'm using select.select() to handle socket input and output, firing something off with sendmail() might mess up that queue somehow. Not sure if that's possible or what to do about it if it is.


RE: Sockets and Sendmail - venquessa - Sep-02-2019

It looks like the socket "s" you get from writables is not in message_queues dictionary.
Are you sure it is?

For best practice protect all this dictionary[key] calls with:

if key in dictionary:
  # stuff
else:
  # log/print error
EDIT: I'm also not sure it's wise to use a socket as a dictionary key, though I'm sure it's possible.