温馨提示×

centos如何调试python程序

小樊
46
2026-09-18 11:13:36
栏目: 编程语言

在 CentOS 上调试 Python 程序,常用的方法和工具如下,按从简单到专业的顺序介绍:


一、最基础的调试方式(print / log)

适合快速定位问题。

python test.py

在代码中加:

print("x =", x)

或使用 logging:

import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("debug info")

二、使用 Python 自带的 pdb(命令行调试器)

无需安装,CentOS 自带。

1. 在代码中打断点

import pdb
pdb.set_trace()

运行:

python test.py

2. 命令行直接调试

python -m pdb test.py

常用 pdb 命令

命令 说明
n 执行下一行
s 进入函数
c 继续执行
l 查看代码
p 变量 打印变量
q 退出

三、使用 ipdb(更好用的 pdb)

支持语法高亮和自动补全。

安装

pip install ipdb

使用

import ipdb
ipdb.set_trace()

四、使用 IDE 远程调试(推荐)

1. PyCharm

  • 本地 Windows / macOS 安装 PyCharm
  • CentOS 上运行 Python
  • 使用 Remote Debug / SSH Interpreter

2. VS Code

  • 安装 Python 插件
  • 使用 Remote - SSH
  • 直接连接 CentOS 调试

五、查看运行状态和错误

1. 查看异常堆栈

python test.py

2. 查看进程

ps -ef | grep python

3. 查看 CPU / 内存

top
htop

六、调试多线程 / 多进程

import faulthandler
faulthandler.enable()

或在启动时:

python -X faulthandler test.py

七、性能调试(卡顿、慢)

1. cProfile

python -m cProfile test.py

2. line_profiler

pip install line_profiler

八、常见问题(CentOS 特有)

1. python 命令不存在

CentOS 7 默认:

python   # Python 2
python3  # Python 3

2. pip 不存在

yum install python3-pip

总结推荐

场景 推荐方式
快速查错 print / logging
命令行调试 pdb / ipdb
专业开发 PyCharm / VS Code
性能问题 cProfile

如果你有具体场景(如:Web 服务、脚本、多线程),我可以给你更针对性的调试方案。

0 踩