python3关闭子进程的两种方式

用scrapy做爬虫的时候需要开多个爬虫子进程,为了定时开启和关闭爬虫子进程,需要对子进程做控制,而关闭进程有两种方法

-----要简单高效,直接看方法2吧-----

方法1:通过获取全部windows进程,获取增量进程方式

该方法是通过获取所有windows进程,将所有进程名为“python.exe”的获取,最后在杀的时候,除了主进程外,全部杀掉
该方法存在的问题在于,如果杀进程的时候刚好有其他人的python在运行,就把其他的也杀了
主要方法:os.kill(pid,signal.SIGTERM)
不是,不是,不是:os.kill(pid, signal.SIGKILL),这个报错

from multiprocessing import Process
import psutil
import signal
import time

main_proce_id = os.getpid()

def get_process_info():
    python_pids = []
    pids = psutil.pids()
    for pid in pids:
        p = psutil.Process(pid)
        pid_name = p.name()
        if pid_name == 'python.exe':
            python_pids.append(pid)
    return python_pids

def byProcess():
    proce = []
    proce.append(Process(target=downApp.main, args=('',)))
    for name_item in presePage.MARKETS['something_info']:
        spider_process = Process(target=targ, args=(name_item['something_name'],))
        proce.append(spider_process)
    for proce_item in proce:
        proce_item.start()
    # 下面这两行千万不能加
    # for proce_item in proce:
    #     proce_item.join()

def targ(spider_name):
    ---you code---
    pass

def kill_spider():
    pids = get_process_info()
    try:
        for pid in pids:
            if pid == main_proce_id:
                continue
            os.kill(pid,signal.SIGTERM)
        print('已关闭子进程')
    except Exception as e:
        print('没有如此进程!!!')

# 晚上8点到第二天早上8点之间执行
def start_in_time():
    while True:
        this_time = int(time.strftime("%H", time.localtime()))
        if this_time == 20:
            print('到点啦,开始')
            WriteLog.writeLog('time','到点啦,开始:%s'%this_time)
            byProcess()
            time.sleep(60 * 60 * 12)
        if this_time == 8:
            print('到点啦,结束')
            WriteLog.writeLog('time', '到点啦,结束:%s' % this_time)
            kill_spider()
            time.sleep(60 * 60 * 12)
        print(WriteLog.localTime() ,'没有到点,不操作')
        time.sleep(120)

if __name__ == '__main__':
    start_in_time()
方法2:通过子进程直接关闭

推荐用这个方法,又简单又准确

from multiprocessing import Process
import time

def byProcess():
    proce = []
    proce.append(Process(target=downApp.main, args=('',)))
    for name_item in presePage.MARKETS['something_info']:
        spider_process = Process(target=targ, args=(name_item['something_name'],))
        proce.append(spider_process)
    for proce_item in proce:
        proce_item.start()
    # 下面这两行千万不能加
    # for proce_item in proce:
    #     proce_item.join()
    return proce

def targ(spider_name):
    ---you code---
    pass

def start_in_time_new():
    '''定时打开和关闭子进程'''
    while True:
        proce = None
        this_time = int(time.strftime("%H", time.localtime()))
        if this_time == 20:
            print('到点啦,开始')
            WriteLog.writeLog('time','到点啦,开始:%s'%this_time)
            proce = byProcess()
            time.sleep(60 * 60 * 12)
        if this_time == 8:
            print('到点啦,结束')
            WriteLog.writeLog('time', '到点啦,结束:%s' % this_time)
            if proce is not None:
                for item in proce:
                    item.terminate()
            time.sleep(60 * 60 * 12)
        print(WriteLog.localTime() ,'没有到点,不操作')
        time.sleep(120)

还有其他通过进程名称杀的,就不写了,用第一种就可以实现。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python处理Windows进程 psutil(Python system and process utilit...
    Zhaifg阅读 22,673评论 0 13
  • 一. 操作系统概念 操作系统位于底层硬件与应用软件之间的一层.工作方式: 向下管理硬件,向上提供接口.操作系统进行...
    月亮是我踢弯得阅读 6,052评论 3 28
  • 描述 你需要去上n门九章的课才能获得offer,这些课被标号为 0 到 n-1 。有一些课程需要“前置课程”,比如...
    6默默Welsh阅读 294评论 0 0
  • 今天第七天, 不再联系那个人。 从以前的亲密无间到现在的形同陌路。 从一开始的无话不谈到现在删了所有信息...
    换什么阅读 257评论 0 0
  • 不如叫自闭症刺客
    莫名_3399阅读 179评论 0 0