Python多处理 - 在子进程之间传递值

时间:2014-02-28 00:08:54

标签: python-2.7 multiprocessing

  1. 我有一个名为grep_phalanx_log的方法,其功能是通过SSH连接机器并grep查找某些值。
  2. 我的main方法将使用不同的主机名/凭证,日志文件名,grep模式调用此方法。
  3. 因此,我需要在PARALLEL中的两个不同服务器中grep寻找SAME模式。如果在一台服务器中找到匹配项,我希望其他服务器停止grep-ing。如果在指定时间内未在两个服务器中找到该模式,则我的方法grep_phalanx_log将返回负值。根据负值,我必须继续其他一些要求。
  4. class eventFlowTestNfx(object)
        def grep_phalanx_log(self, host_name, username, password, grep_cmd, timeout=10, time_to_monitor=20):
            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            Log.info("Grep command to be executed: %r" % grep_cmd)
            try:
                ssh_client.connect(host_name, username=username, password=password, timeout=timeout)
                end_time = time.time() + time_to_monitor
                while time.time() < end_time:
                    ssh_stdin, ssh_stdout, ssh_stderr =  ssh_client.exec_command(grep_cmd)
                    output = ssh_stdout.read()
                    if not output:
                        time.sleep(1)
                    else:
                        Log.info("NFX: Match message from %r is %r" % (host_name, output))
                        return output
                if not output:
                    Log.error("FAILED: Message not processed.")
                    Log.error("Host Name: %r and grep command: %r" % (host_name, grep_cmd))
                    raise Exception("NFX agent could not process message")
            except:
                Log.error("End to End flow is broken, check the logs!")
                return -1
        def main(self):
            for cr_dict in correlation_list:
                cr_process = multiprocessing.Process(target=self.grep_phalanx_log(), args=(cr_dict["host"], cr_dict["username"], cr_dict["password"], cr_received_cmd_skeleton,))
                cr_process.start()
    

    所以,我让我的代码盯着2个进程,我不确定他们将如何相互通话并终止另一个。

1 个答案:

答案 0 :(得分:0)

您可以将time.sleep(1)替换为:

if not output.strip(): # blank output
    is_found = found.wait(1) # sleep >= 1 second unless found
    if is_found:  
        break # stop grepping
else: # found something
    found.set() 
    ...
    return output

其中found = multiprocessing.Event():在父进程中创建它并传递给每个子进程。