如何在python子进程完成时执行post操作

时间:2017-04-12 09:42:13

标签: python elasticsearch subprocess logstash

我有一个python脚本,它创建一个子进程来运行索引操作(logstash到elasticsearch)。

代码段如下,

process = subprocess.Popen([logstash, '-f', sample.conf],
                                   stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

我不调用process.wait(),因为我创建的子进程需要独立于脚本的其余部分运行。

但是我必须在子进程完成时更新数据库记录。我正在运行的索引操作不允许我创建一个允许我更新数据库的帖子作业调用。

如何使用python子进程处理这个问题?我将作业的PID存储在一个文本文件中,但是我想要一个知道子进程何时完成的触发器来执行下一个脚本。

2 个答案:

答案 0 :(得分:0)

您可以在线程中创建进程。您可以从线程中wait,以便获得输出,并且它是非阻塞的

import threading
import subprocess

def run_command():
    p = subprocess.Popen([logstash, '-f', sample.conf],
                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = p.stdout.read()
    p.wait()
    # now your command has ended, do whatever you like

并在主线程中:

t = threading.Thread(target=run_command)
t.start()
# continue with main processing

答案 1 :(得分:0)

由于您似乎在某处隐藏了process变量,之后您可以在调用其poll方法后检查其returncode attribute

如果该流程已完成,则其returncode值不会为None,您可以更新数据库。

相关问题