流产后的Python无限循环

时间:2011-04-27 11:56:07

标签: python

我有这段代码:

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()  

问题是,当我按ctrl + c中止程序时,它会立即跳转到" xlog / syslog"中的新行的无限循环。你看到了问题吗? :/我需要添加一些代码,也可以中止这两个线程。

3 个答案:

答案 0 :(得分:2)

扩展Fantasizer所说的内容,请尝试以下代码:

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

答案 1 :(得分:1)

您可能对signal模块感兴趣以更优雅的方式处理SIGINT和其他模块

答案 2 :(得分:0)

使用ctrl + c,python会引发KeyboardInterrupt,所以你可以捕获它并打破你的while循环。