Python 中止后无限循环

2023-12-10

我有这个代码:

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 中的新行”的无限循环。你看到问题了吗? :/我需要添加一些代码,这可能也会中止这两个线程。


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

while True:
    try:
        print('running')
    except KeyboardInterrupt:
        print('stop')
        exit(0)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中止后无限循环 的相关文章

随机推荐