Python endless loop after interruption

I have this code:

class LogDigger: @staticmethod def RunInfiniteLoopSyslog(): while True: line = LogDigger.syslog_p.stdout.readline() Utils.log("New line in syslog: %s" % line.rstrip('\n')) @staticmethod def RunInfiniteLoopXlog(): while True: line = LogDigger.xlog_p.stdout.readline() Utils.log("New line in xlog: %s" % line.rstrip('\n')) @staticmethod def StartProcesses(): LogDigger.syslog_p = subprocess.Popen(['tail', '-f', '-n0', '/var/log/syslog'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) LogDigger.xlog_p = subprocess.Popen(['tail', '-f', '-n0', '/var/log/mail-xlog'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) syslog_thread = threading.Thread(target = LogDigger.RunInfiniteLoopSyslog) xlog_thread = threading.Thread(target = LogDigger.RunInfiniteLoopXlog) syslog_thread.start() xlog_thread.start() 

The problem is that when I press ctrl + c to interrupt the program, it instantly goes into the endless loop "New line in xlog / syslog". Do you see the problem?: / I need to add some code that may interrupt these two threads as well.

+1
source share
3 answers

Turning to what Fantasizer said, try the code below:

 while True: try: print('running') except KeyboardInterrupt: print('stop') exit(0) 
+2
source

You may be interested in the signal module to handle SIGINT and others in a more graceful way.

+1
source

Using ctrl + c, python creates a KeyboardInterrupt , so you can catch this and break your while loops.

0
source

All Articles