You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多进程进程异常终止后无法稳定重启问题求助

问题分析与修复方案

核心问题点

  1. 致命拼写错误:主进程重启爬虫时,误写为serlog_bot(正确应为scraper),导致重启时触发NameError,主进程监控循环崩溃,无法完成重启。
  2. 未处理异常:爬虫进程(scraper)的Selenium操作、Telegram读取进程(telegram_read)的网络连接均未做异常捕获,任何未处理的异常都会直接导致进程终止。
  3. 粗暴的进程终止方式:使用kill()方法终止进程,跨平台兼容性差,且未等待进程完全退出就重建,可能引发资源冲突。
  4. 资源泄漏:爬虫进程崩溃时未关闭Chrome Driver,残留进程会影响后续重启的Driver初始化。

修复后的代码

from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import time
import telegram
from telethon import TelegramClient, events
import asyncio
from multiprocessing import Process, Queue

# 全局初始化Telegram Bot实例,避免重复创建
bot = telegram.Bot(token=key)

def telegram_send(message: str):
    try:
        asyncio.run(bot.send_message(chat_id=CHAT_ID, text=message))
    except Exception as e:
        print(f"发送消息失败: {e}")

def telegram_read(messages):
    while True:
        try:
            client = TelegramClient('anon', API_ID, API_HASH)

            @client.on(events.NewMessage(chats=BOT_NAME))
            async def my_event_handler(event):
                message = event.raw_text
                messages.put(message)

            client.start()
            client.run_until_disconnected()
        except Exception as e:
            print(f"Telegram读取进程异常: {e}")
            time.sleep(10)  # 异常后等待10秒再重连

def scraper(msg_list):
    driver = None
    while True:
        try:
            if not driver:
                driver = webdriver.Chrome()
            
            # 此处放置你的爬虫逻辑
            # Scrapes the site

            if check():  # 找到目标内容时发送通知
                telegram_send('Found')

            time.sleep(10)
        except WebDriverException as e:
            print(f"爬虫Driver异常: {e}")
            if driver:
                driver.quit()
                driver = None  # 标记需要重新初始化Driver
            time.sleep(10)
        except Exception as e:
            print(f"爬虫进程异常: {e}")
            time.sleep(10)

if __name__ == '__main__':
    msg_list = Queue()

    # 初始化进程
    main_bot = Process(target=scraper, args=(msg_list, ))
    main_bot.start()

    telegram_bot = Process(target=telegram_read, args=(msg_list, ))
    telegram_bot.start()

    while True:
        # 监控并重启爬虫进程
        if not main_bot.is_alive():
            print("爬虫进程已终止,正在重启...")
            if main_bot.is_alive():
                main_bot.terminate()
            main_bot.join(timeout=10)  # 等待进程退出,超时强制结束
            main_bot = Process(target=scraper, args=(msg_list,))
            main_bot.start()

        # 监控并重启Telegram读取进程
        if not telegram_bot.is_alive():
            print("Telegram读取进程已终止,正在重启...")
            if telegram_bot.is_alive():
                telegram_bot.terminate()
            telegram_bot.join(timeout=10)
            telegram_bot = Process(target=telegram_read, args=(msg_list, ))
            telegram_bot.start()    

        time.sleep(60)

关键修改说明

  • 修复了serlog_bot的拼写错误,确保爬虫进程能正常重启。
  • 给scraper添加了Selenium异常捕获,崩溃时自动关闭Driver并重新初始化。
  • 给telegram_read添加了循环重连逻辑,网络断开后自动重试。
  • 优化进程重启流程:先终止进程、等待退出,再重建启动,避免资源冲突。
  • 全局复用Telegram Bot实例,减少重复初始化的开销与错误。

内容的提问来源于stack exchange,提问作者Francesco Fadda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:17:05