python - subprocess.poll() 不工作

标签 python subprocess python-2.4

我无法让 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'

我在这里做错了什么?

最佳答案

您在 self.process 被赋值之前调用了 self.process.poll()。当您启动线程时,它会先调用您的 run() 方法,但您的主要代码会继续运行。在 job1.run() 完成任何有用的工作之前,您最终调用了 job1.alive()

关于python - subprocess.poll() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25170343/

相关文章:

python - groupby 内迭代排序

python - Bash 正在等待 python 子进程

python - urllib2:如何安装代理和 http 基本身份验证处理程序作为开启器?

python: [Errno 10054] 现有连接被远程主机强行关闭

python - 将 caffe 与 c++ 或 python 连接时出现问题

Python loadarff 对字符串属性失败

python - 如何使用 Python 2.4 解压缩文件?

python - 如何在 python 2.4 中安全地打开/关闭文件

python - 特定行 Pandas 数据框的总和

Python 在终止后捕获子进程输出