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