Skip to main content
 首页 » 编程设计

python之使用 pid 轮询子进程

2025年04月02日16java哥

<分区>

我有一个 Django 项目,允许用户一次启动多个子进程。这些过程可能需要一些时间,因此用户可以继续使用应用程序的其他方面。在任何情况下,用户都可以查看所有正在运行的进程并轮询其中任何一个以检查其是否结束。为此,我需要使用它的 pid 来轮询进程。 Popen.poll() 需要一个 subprocess.Peopen 对象,而我所拥有的只是该对象的 pid。我怎样才能得到想要的结果?

在 models.py 中:

class Runningprocess(models.Model): 
    #some other fields 
    p_id=models.CharField(max_length=500) 
    def __str__(self): 
        return self.field1 

在 views.py 中:

def run_process(): 
    .... 
    p= subprocess.Popen(cmd, shell =True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    new_p=Runningprocess()   
    new_p.p_id=p.pid 
    .... 
    new_p.save() 
    return HttpResponseRedirect('/home/')    
 
def check(request,pid): 
    #here i want to be able to poll the subprocess using the p_id e.g something like: 
     checkp = pid.poll() #this statement is wrong 
     if checkp is None: 
           do something 
     else: 
           do something else 

我只需要一个有效的语句而不是'checkp = pid.poll()'