温馨提示×

ubuntu为何python占用高

小樊
65
2026-09-16 15:32:09
栏目: 编程语言

在 Ubuntu 上发现 Python 进程 CPU 或内存占用很高,通常不是 Python 本身的问题,而是某个由 Python 写的程序/服务在干活或出错了。下面按常见原因给你梳理一下。


一、最常见原因

1️⃣ 系统自带服务(很常见)

Ubuntu 里很多系统组件是用 Python 写的,例如:

  • apt、apt-get
  • unattended-upgrades(自动更新)
  • ubuntu-software / snap
  • networkd-dispatcher
  • cron 里跑的 Python 脚本

✅ 检查方式:

top

或

ps aux | grep python

如果你看到:

/usr/bin/python3 /usr/bin/unattended-upgrade

那就是系统自动更新在跑。


2️⃣ 自动更新(unattended-upgrades)

这是 CPU 高占用的头号原因。

systemctl status unattended-upgrades

临时关闭:

sudo systemctl stop unattended-upgrades

长期关闭(不推荐服务器):

sudo dpkg-reconfigure unattended-upgrades

3️⃣ 你在跑的 Python 程序

  • 爬虫
  • 机器学习 / PyTorch / TensorFlow
  • 死循环 bug
  • 日志没限制导致内存暴涨

可以用:

py-spy top --pid <PID>

或

htop

4️⃣ Cron 定时任务

crontab -l
sudo crontab -l

有时候 Python 脚本:

  • 每分钟跑一次
  • 脚本卡死
  • 越积越多

5️⃣ Snap / 容器环境

Snap 应用(如 VS Code、Chromium)内部常带 Python。

snap list

二、内存高 vs CPU 高 区别

现象 可能原因
CPU 高 死循环、计算任务、更新
内存高 内存泄漏、爬虫、缓存未释放
突然暴涨 OOM、异常脚本

三、快速排查套路(推荐)

top

找到 Python PID

ps -fp <PID>

看是:

  • 系统进程?
  • 你自己的脚本?
  • 哪个路径?

四、如果你想进一步定位

可以告诉我:

  1. top 里看到的具体进程名
  2. 是 CPU 高还是内存高
  3. 是 桌面版还是服务器版 Ubuntu
  4. 是不是刚装完系统 / 刚更新过

我可以直接帮你判断是“正常现象”还是“需要修的问题”。

0 踩