subprocess.poll() 无法工作

1 投票
1 回答
3084 浏览
提问于 2025-04-18 16:18

我在任何情况下都无法让subprocess.poll()正常工作。它总是报错:

Traceback (most recent call last):
  File "./JobScheduler.py", line 41, in ?
    while job1.alive():
  File "./JobScheduler.py", line 26, in alive
    if self.process.poll() is None:
AttributeError: 'NoneType' object has no attribute 'poll'

这是我的代码:

#!/usr/bin/python (using version 2.4)
import sys, subprocess, threading, random, time, logging

class Command(threading.Thread):
    def __init__(self, cmd):
        super(Command, self).__init__()
        self.cmd        = cmd
        self.process    = None
        self.jobid      = None
        self.returncode = None

    def run(self):
        print "%s: starting job..." % self.getName()
        self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, shell=True)
        out, err = self.process.communicate()
        self.returncode = self.process.returncode
        print "Process complete:"
        print "  returncode=" + str(self.returncode)
        print "  output=" + out

    def alive(self):
        if self.process.poll() is None:
            return True
        else:
            return False

    def getJobID(self):
        return self.jobid

job1 = Command(cmd)
job1.start()
job2 = Command(cmd)
job2.start()
print "MAIN: Jobs started."

while job1.alive():
    print "job still running."
    time.sleep(10)

sys.exit(0)

我尝试了各种方法使用poll(),但就是无法让它正常工作。在while()循环执行的时候,进程仍然在运行。

示例输出:

# ./JobScheduler.py 
Thread-1: starting job...
Thread-2: starting job...
MAIN: Jobs started.
Traceback (most recent call last):
  File "./JobScheduler.py", line 41, in ?
    while job1.alive():
  File "./JobScheduler.py", line 26, in alive
    if self.process.poll() is None:
 AttributeError: 'NoneType' object has no attribute 'poll'

我到底哪里做错了呢?

1 个回答

4

你在给 self.process.poll() 这个方法打电话的时候,self.process 还没有被赋值。也就是说,当你启动线程的时候,它会先调用你的 run() 方法,但你的主代码还是会继续执行。这样一来,你就会在 job1.run() 还没做任何有用的事情之前,就先调用了 job1.alive()

撰写回答