【发布时间】:2014-04-24 13:10:28
【问题描述】:
我需要在我的包的一部分上运行unittest,对我来说最好的办法是控制启动它,然后杀死由multiprocessing 模块产生的所有进程。
这就是我要说的:
test.py
import logging
import multiprocessing
import time
import random
log = logging.getLogger(__name__)
def start_consumers(conf, worker_count=5):
manager = WorkerManager(conf, worker_count)
manager.start()
class WorkerManager():
def __init__(self, conf, worker_count=5):
self.workers = []
for num in range(worker_count):
self.workers.append(WorkHandler(conf))
def start(self):
for worker in self.workers:
worker.daemon = True
worker.start()
print 'started'
for worker in self.workers:
worker.join()
class WorkHandler(multiprocessing.Process):
def __init__(self, conf, *args, **kwargs):
super(WorkHandler, self).__init__(*args, **kwargs)
self.conf = conf
self.name = str(random.randint(0,100))
def run(self):
while True:
print self.conf['foo'], self.name
time.sleep(3)
if __name__ == "__main__":
conf = {'foo': 'bar'}
start_consumers(conf)
现在如果我从 linux 终端运行这个测试,我可以看到打印语句,如果我这样做的话:
ps aux | grep python我看到所有子进程都产生了:
sergey 4081 0.0 0.1 71684 13164 pts/3 S+ 08:58 0:00 python
sergey 4108 0.3 0.0 39092 6472 pts/3 S+ 08:59 0:00 python test.py
sergey 4109 0.0 0.0 39092 4576 pts/3 S+ 08:59 0:00 python test.py
sergey 4110 0.0 0.0 39092 4568 pts/3 S+ 08:59 0:00 python test.py
sergey 4111 0.0 0.0 39092 4576 pts/3 S+ 08:59 0:00 python test.py
sergey 4112 0.0 0.0 39092 4584 pts/3 S+ 08:59 0:00 python test.py
sergey 4113 0.0 0.0 39092 4580 pts/3 S+ 08:59 0:00 python test.py
sergey 4115 0.0 0.0 13588 944 pts/7 S+ 08:59 0:00 grep --color=auto python
现在,如果我尝试使用 subprocess 运行相同的 test.py,一切正常,直到我需要将它们全部杀死:
>>> import subprocess as s
>>> p = s.Popen(['python', 'test.py'], stdout=s.PIPE)
问题:
当我在终端中按下Ctrl+C 时,使用这个变量p 来实现类似行为的最优雅的方法是什么?
换句话说,我想获得类似于pkill -f "test.py"的结果
更新:
p.kill() 或 p.terminate() 不能满足我的需要:
这是我做了它们之后的结果:
sergey 4438 0.0 0.0 0 0 pts/3 Z+ 09:16 0:00 [python] <defunct>
sergey 4439 0.0 0.0 39092 4572 pts/3 S+ 09:16 0:00 python test.py
sergey 4440 0.0 0.0 39092 4568 pts/3 S+ 09:16 0:00 python test.py
sergey 4441 0.0 0.0 39092 4576 pts/3 S+ 09:16 0:00 python test.py
sergey 4442 0.0 0.0 39092 4580 pts/3 S+ 09:16 0:00 python test.py
sergey 4443 0.0 0.0 39092 4580 pts/3 S+ 09:16 0:00 python test.py
【问题讨论】:
标签: python linux subprocess multiprocessing