温馨提示×

ubuntu怎么测试python代码

小樊
41
2026-10-21 23:34:25
栏目: 编程语言

在 Ubuntu 上测试 Python 代码,常见方式有以下几种,从最简单到更规范依次说明:


一、直接运行 Python 代码(最快)

1. 交互式运行

python3

然后输入:

print("hello")

按 Ctrl + D 退出。

2. 运行 .py 文件

python3 test.py

二、写简单测试(手动验证)

例如 test.py:

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

print(add(1, 2))

运行:

python3 test.py

三、使用 assert 做基础测试

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

assert add(1, 2) == 3
assert add(-1, 1) == 0
print("测试通过")

运行:

python3 test.py

四、使用 unittest(Python 内置)

示例

test_math.py:

import unittest

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

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

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

运行:

python3 test_math.py

五、使用 pytest(推荐,更简洁)

安装

pip3 install pytest

示例

test_sample.py:

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

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

运行:

pytest

六、虚拟环境(推荐开发使用)

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

退出环境:

deactivate

七、常见检查命令

python3 --version
pip3 --version
which python3

如果你是:

  • ✅ 初学者 → 用 python3 xxx.py
  • ✅ 写项目 → 用 pytest
  • ✅ 面试/作业 → unittest 或 assert

可以告诉我你是测试什么类型的代码(算法 / Web / 脚本 / 作业),我可以给你更具体的示例。

0 踩