func_timeout icon indicating copy to clipboard operation
func_timeout copied to clipboard

does not work with tkinter and socket and real-time print

Open davejakenic opened this issue 3 years ago • 1 comments

I have a python code of 1000 LOC that I am happy to share.

It uses a client with GUI and a server. Upon user.__button_click(), the client sends a request to the server via socket and prints label text in real time on the program state. The server receives the request and then there is a back-and-forth between server and client, based on the kind of request. The server reacts on a request in the server.__serve_client() routine. The communication is with python socket.socket, .connect() and .listen(1) .

Naturally, I put the following python code around user.__button_click() and server.__serve_client() from above:

def run_function_with_timelimit(function,arguments,max_wait,default_value):
    try: return func_timeout.func_timeout(max_wait,function,args=arguments)
    except func_timeout.FunctionTimedOut: print("took too long")
    except Exception as e: print(f"error occured: {e}.")
    return default_value

Now nothing works anymore. Particularly, both the server and client repeatedly wait for 10 seconds and then print "took too long".

If you want to help me, point me to where I shall send you my code. Alternatively, I am happy for any instructions in this place on how to fix the error.

davejakenic avatar Aug 07 '22 12:08 davejakenic

Hello, are you still there? Sorry, I have been away for a while.

I'm not sure what your issue is, but for socket work func_timeout probably isn't the appropriate library. What you want to do is use non-blocking socket methods to communicate between the two. Aborting a blocked I/O socket operation (the default for sockets) is almost certain to leave the socket in a bad, broken state.

You can use socket.setblocking(0) to set the socket to a non-blocking state. In this mode, recv() will return right away if nothing is waiting in the kernel buffer, so you'll have to do a loop where you check for data and use it if available and complete, otherwise you sleep for a short bit and try again, up to a maximum timeout.

I can help you through the basics of non blocking socket programming if you'd like

kata198 avatar Apr 23 '23 08:04 kata198