bobjacobsen / python-openlcb

MIT License
2 stars 1 forks source link

Getting Ctrl-C to work consistently #6

Closed Poikilos closed 2 months ago

Poikilos commented 5 months ago

Possible causes of problem:

Places where KeyboardInterrupt doesn't get raised (or takes a minute, possibly a timing issue requiring multiple tries if the time is missed. Tested on Windows):

bobjacobsen commented 5 months ago

The bare try...except clauses in e.g. canlink.py come from Swift guard ... else ... statements. A guard statement checks for errors in or a None return from some expression, and invokes it's else clause if there are any. Unfortunately, it doesn't give any clue as to what the errors that can be encountered are.

Some of them might be due to a difference in how dictionary access works in Python vs Swift. If you look up a non-existent key in Swift, you just get a null (None) result. In Python, unless you've checked first, you get an exception.

bobjacobsen commented 5 months ago

I think what's preventing ctrl-c from working is this: https://peps.python.org/pep-0475/

The socket recv call is soaking them up and not allowing them to terminate the program. I've tried a couple recommended ways to handle this:

Poikilos commented 5 months ago

The bare try...except clauses in e.g. canlink.py come from Swift guard ... else ... statements. A guard statement checks for errors in or a None return from some expression, and invokes it's else clause if there are any. Unfortunately, it doesn't give any clue as to what the errors that can be encountered are.

Some of them might be due to a difference in how dictionary access works in Python vs Swift. If you look up a non-existent key in Swift, you just get a null (None) result. In Python, unless you've checked first, you get an exception.

If you want to use later logic that checks for None instead of having an exception, you can replace foo[key] with foo.get(key) and it will return None if not present.

bobjacobsen commented 5 months ago

^C seems to be working now. Would appreciate hearing if it's working for you too.

bobjacobsen commented 2 months ago

ctrl-C seems to be working consistently for me now. Are you still having trouble with it?

Poikilos commented 2 months ago

Thanks for checking into this. I removed all bare excepts and the same behavior occurred. Setting the socket timeout "fixed" it but the expected behavior seems for the program to run in the background. I will send a PR that allows the user to set the timeout where appropriate to their specific case rather than the example case. I'll also ensure KeyboardInterrupt is re-raised just to be sure.