Reputation: 342
Im programming a client-server in python, and them when working are sending keepalive packets every second.
I need the client to read from my keyboard an action to send a special packet to the server, but when reading I can't stop sending keepalive packets, so if I read by standard way, it blocks and stops the keepalive packet sending.
The perfect behaviour would be to write in console while keepaliving, and when pressing "enter" process that text.
Any ideas please?
Thanks!
Upvotes: 0
Views: 517
Reputation: 414325
Another way to read user input on Unix without blocking (for too long) is to use an alarm:
from signal import SIGALRM, alarm, signal
class Alarm(Exception):
pass
def alarm_handler(*args):
raise Alarm
def raw_input_alarm(prompt='', timeout=None):
if timeout is None: # no timeout
return raw_input(prompt)
# set signal handler
signal(SIGALRM, alarm_handler)
alarm(timeout) # produce SIGALRM in `timeout` seconds
try:
return raw_input(prompt)
except Alarm:
return '' # timeout happened
finally:
alarm(0) # cancel alarm
print(repr(raw_input_alarm(timeout=1)))
alarm
expects integer number of seconds. If you want smaller timeout; see signal.setitimer()
.
Upvotes: 0
Reputation: 342
Found it, using select.select I could do that, like this:
selectList = [sktTCP,sys.stdin]
(read, write, exc) = select.select(selectList, [], [], 0 )
I hope it'll help someone!
Upvotes: 1
Reputation: 2821
This is a threading issue basically. I would suggest looking into managing your network connections using Twisted. It can work asynchronously, leaving you able to pick up key presses.
Upvotes: 0