温馨提示×

ubuntu怎样测python代码

小樊
54
2026-09-07 12:22:39
栏目: 编程语言

在 Ubuntu 上“测 Python 代码”通常有以下几种常见含义,我分别说明,你可以看哪个符合你的需求:


一、运行 / 测试 Python 代码是否可运行

1. 先确认 Python 已安装

python3 --version

如果没有安装:

sudo apt update
sudo apt install python3

2. 运行 Python 脚本

假设你有 test.py:

python3 test.py

3. 交互式测试

python3

然后直接在终端写代码测试。


二、单元测试(写测试用例)

使用内置 unittest

test_demo.py:

import unittest

def add(a, b):
    return a + b

class TestAdd(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)

if __name__ == '__main__':
    unittest.main()

运行:

python3 test_demo.py

使用 pytest(更常用)

安装:

pip3 install pytest

测试文件 test_demo.py:

def add(a, b):
    return a + b

def test_add():
    assert add(1, 2) == 3

运行:

pytest

三、代码风格 / 质量检查

1. 语法检查

python3 -m py_compile test.py

2. 代码规范(PEP8)

pip3 install flake8
flake8 test.py

3. 类型检查

pip3 install mypy
mypy test.py

四、性能测试

python3 -m timeit "x=1+1"

或在代码里:

import time
start = time.time()
# your code
print(time.time() - start)

五、虚拟环境(推荐)

python3 -m venv venv
source venv/bin/activate
pip install pytest

如果你能具体说一下:

  • 是想跑一下代码
  • 还是写自动化测试
  • 还是测性能 / 覆盖率

我可以给你更针对性的示例。

0 踩