在单独的线程中运行日志记录筛选器 - Python

时间:2015-12-10 17:15:58

标签: python multithreading subprocess multiprocessing

我有一个日志记录过滤器,用于检查要更改的环境变量,我希望它在与设置环境变量的进程分开的线程中运行(在后台)。

我正在尝试做的事情:每次在我的代码中调用logging.ERROR时,都会提醒用户该错误并提示他们是否要继续。另外,过滤器和提示工作正确,但是,当我把它们放在一起时,我有一个问题。我需要在后台运行过滤器,以便提示用户可以同时运行的代码(现在,过滤器首先执行,并且过滤器中的while循环超时后显示提示,此时它是无用的)。

我的过滤器代码:

class ErrorFilter(logging.Filter):
  def __init__(self,level):
    self.level = level
    thread = threading.Thread(target=self.filter,args=())
    thread.daemon = True
    thread.start()

  def filter(self,record):
    if record.levelno == self.level:
        os.environ["ERROR_FLAG"] = "True"
        timeout = time.time() + 60*1 #set the timeout to 1 minute
        while True:
            print "waiting..."
            keep_going = os.environ.get("CONTINUE_FLAG")
            #wait for user to respond
            if keep_going == "False" or time.time() > timeout:
                print "oops there's a problem, quitting."
                break
            if keep_going == "True":
                print "Continuing"
                break
        os.environ["CONTINUE_FLAG"] = "None"

我有另一个“监听”ERROR_FLAG的简短方法,然后使用以下方法请求输入:

def continueAsk(message, title="Warning! Continue?", yn=("Yes","No")):
  yes = set(['yes','y', 'ye', '', 'canhaz'])
  no  = set(['no','n', 'lolzno'])

  tryLimit = 0
  while tryLimit < 100:
    sys.stdout.write(message + ": ")
    choice = raw_input().lower()
    if choice in yes:
        return True
    elif choice in no:
        return False
    else:
        tryLimit+=1
        sys.stdout.write("Please respond with 'yes' or 'no'.")

修改

我也尝试在我的过滤器中使用multiprocessing,如下所示:

from multiprocessing import Process, Queue
def __init__(self,level):
    self.level = level
    queue = Queue()
    p = Process(target=self.filter,args=("hi"))
    p.start()
    p.join()

我已经尝试设置我的过滤器,因此它在不同的线程中运行,但到目前为止我没有运气(过滤器仍然先运行,然后是提示)并且我以前从未使用过多线程。我知道这不是记录器的传统用法,但我很感激任何输入。

查看subprocessmultiprocess文档,我认为其中一个可能也有效但不确定。

0 个答案:

没有答案
相关问题