Python subprocess.poll()不工作
我无法使subprocess.poll()在任何情况下工作。它不断抱怨:Python subprocess.poll()不工作,python,subprocess,python-2.4,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' obj
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.poll()
,然后才为self.process
赋值。当您启动线程时,它首先调用run()
方法,但主代码继续运行。在job1.run()
完成任何有用的工作之前,您将调用job1.alive()
。在self.process
被赋值之前,您将调用self.process.poll()
。当您启动线程时,它首先调用run()
方法,但主代码继续运行。在job1.run()
还没有完成任何有用的工作之前,你就调用了job1.alive()
。这就是为什么我要添加一个self.\u lock
在我对你关于这个主题的其他问题的回答中:很好的老式比赛条件。为什么不.wait()
运行方法中的进程和.join()
主线程中的“runner”线程?这就是为什么我在添加一个self时很麻烦的原因这是一个很好的老式竞速条件。为什么不.wait()
运行方法中的进程和.join()
主线程中的“runner”线程呢?那么正确的方法是什么呢?如果我在while循环之前在sleep(10)中硬编码,它就会工作。但硬编码睡眠声明对我来说似乎并不可靠。在这个测试用例中,10秒可能足够了,但加载的系统可能不够。您可以在\uuuu init\uuuu
方法中初始化self.process
,然后在run
方法中调用communicate()
。这样,它将永远不会是None
。Ahh可以在init()中调用Popen。我一定试过所有可能的东西,除了那个。谢谢!那么,正确的做法是什么呢?如果我在while循环之前在sleep(10)中硬编码,它就会工作。但硬编码睡眠声明对我来说似乎并不可靠。在这个测试用例中,10秒可能足够了,但加载的系统可能不够。您可以在\uuuu init\uuuu
方法中初始化self.process
,然后在run
方法中调用communicate()
。这样,它将永远不会是None
。Ahh可以在init()中调用Popen。我一定试过所有可能的东西,除了那个。谢谢!