1

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, when I press ctrl+c to abort the program, it instantly jumps into infinite loop of "New line in xlog/syslog". Do you see the problem ? :/ I need add some code, which aborts also those two threads maybe.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
Mejmo
  • 2,363
  • 9
  • 35
  • 54

3 Answers3

2

Expanding on what Fantasizer has said, try the code below:

while True:
    try:
        print('running')
    except KeyboardInterrupt:
        print('stop')
        exit(0)
AnalyticsBuilder
  • 4,111
  • 4
  • 24
  • 36
1

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

neurino
  • 11,500
  • 2
  • 40
  • 63
0

With a ctrl+c, python raises a KeyboardInterrupt, so you could catch that and break your while loops.

erbridge
  • 1,376
  • 12
  • 27