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

为什么Python线程在Mac可正常向控制台打印、在Ubuntu运行却无输出

问题根因
  • 核心原因:代码仅将抓取任务提交给了事件循环绑定的线程池,未等待所有任务执行完成,主线程提交完任务后会直接退出。Ubuntu环境下进程资源回收速度更快,后台执行的scraper线程还没运行到打印逻辑就被强制销毁,因此没有输出;Mac环境下进程退出前有短暂的缓冲窗口,刚好够线程跑完逻辑,所以能看到打印结果。
  • 次要潜在原因:Ubuntu环境缺少Chrome/Chromium运行依赖、./chromedriver相对路径对应文件不存在、chromedriver和浏览器版本不匹配,都会导致scraper函数执行时报错,而线程池内抛出的异常默认不会直接输出到终端,因此看不到错误提示。
解决方案

1. 改造异步逻辑,等待所有任务执行完成

调整代码结构,收集run_in_executor返回的Future对象,通过asyncio.gather等待全部任务执行结束,同时增加异常捕获逻辑方便排查问题,修改后的代码如下:

import asyncio
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from concurrent.futures.thread import ThreadPoolExecutor

executor = ThreadPoolExecutor(2)

options = Options()
options.headless = True
# Ubuntu无头模式必须加以下两个参数避免浏览器启动失败
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")

def scraper(url: str):
    try:
        driver = webdriver.Chrome('./chromedriver', options=options)
        driver.get(url)
        print(driver.title)
        print(driver.current_url)
        # 用quit代替close,彻底销毁浏览器进程避免残留
        driver.quit()
    except Exception as e:
        # 主动捕获打印异常,方便排查问题
        print(f"抓取{url}失败:{str(e)}")

async def main():
    urls = [
        'https://example.com',
        'https://wikipedia.org'
    ]
    loop = asyncio.get_running_loop()
    # 收集所有异步任务
    tasks = [loop.run_in_executor(executor, scraper, url) for url in urls]
    # 阻塞等待所有任务执行完成
    await asyncio.gather(*tasks)

if __name__ == "__main__":
    asyncio.run(main())

2. 排查Ubuntu环境依赖

  • 执行./chromedriver --version和google-chrome --version(或chromium-browser --version)核对版本,二者大版本号必须完全一致
  • 若浏览器启动报错,执行命令安装缺失依赖:sudo apt install -y chromium-browser chromium-chromedriver libnss3 libgconf-2-4 libfontconfig1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:15:01