Ubuntu 22.04 locust 安装与命令参数详解
在 Ubuntu 22.04 上通过 python3 虚拟环境安装 locust 2.46.0,并逐参数实测 -f/-H/-u/-r/-t/--headless/--web-port/-P/--csv/--loglevel/--help 的输入与回显,覆盖 HttpUser 脚本编写、Web UI 与 headless 压测。
Ubuntu 22.04 locust 安装与命令参数详解
目标:在 Ubuntu 22.04 上用 Python 虚拟环境安装 locust 2.46.0,并逐参数实测
-f指定脚本、-H目标主机、-u用户数、-r生成速率、-t运行时长、--headless无头模式、--web-port/-PWeb 端口、--csv导出、--loglevel日志级别及--help,通过软件定义的一个 HttpUser 压测脚本跑真实 headless 回显。本文命令与输出均为 Ubuntu 22.04(locust 2.46.0)实测回显。
一、环境信息
- 操作系统:Ubuntu 22.04.5 LTS(Jammy Jellyfish)
- Python:3.10.12(
/usr/bin/python3) - pip:22.0.2(系统),虚拟环境内为 venv 自带 pip
- locust 版本:2.46.0(安装在 Python 虚拟环境
/opt/data/locust/venv) - 压测机主机名:
ubuntu-loadtester,网卡 eth0,IP172.26.0.4/16 - 压力测试目标:
http://172.26.0.2:8080/(HTTP 服务,提供 index.html 等资源) - 测试脚本与数据目录:
/opt/data/locust/(locustfile.py、venv/、result_*.csv)
二、工具概述
locust 是一个用 Python 编写的可编程、分布式负载压力测试工具,核心思想是用「软件定义的用户」(模拟用户)以指定数量与生成速率持续向目标发 HTTP 请求,并实时统计请求数、失败数、响应延迟、QPS 等指标。相比 wrk/ab 这类固定式压测,locust 的优势是其真正的可编程性——压测场景用 Python 写成(HttpUser + @task),可定义会话、权重、等待时间,且天然支持多机主从(master/worker)分布式扩展。它提供 Web UI 与无头(headless)两种运行方式。本文在 Ubuntu 22.04 上安装 2.46.0 并逐参数实测。
⚠️ 注意:locust 的
-u是「模拟用户数」(软件定义的并发任务数),并非传统意义的 TCP 连接数;实际并发取决于目标服务能承受的程度。压测目标必须是可建立 TCP 并返回 HTTP 响应的真实 HTTP 服务(如python3 -m http.server、nginx 等)。
三、安装
3.1 安装 python3 / pip / venv
Ubuntu 22.04 官方仓库自带 Python 3.10 与 pip。缺 python3-pip/python3-venv 时先安装:
sudo apt update
sudo apt install -y python3 python3-pip python3-venv
确认版本:
python3 --version
pip3 --version
Python 3.10.12
pip 22.0.2 from /usr/lib/python3/dist-packages (pip 3.10)
3.2 创建虚拟环境并安装 locust(推荐)
为避免污染系统 Python 环境(新版 Ubuntu 常启用 PEP 668 的 externally-managed 限制),推荐用虚拟环境隔离安装:
mkdir -p /opt/data/locust
python3 -m venv /opt/data/locust/venv
/opt/data/locust/venv/bin/pip install locust
安装完成(末尾回显,核心依赖含 gevent/geventhttpclient/flask,locust 主包为 locust-2.46.0):
Collecting locust
Downloading locust-2.46.0-py3-none-any.whl (1.5 MB)
Collecting gevent
Downloading gevent-25.9.1-py3-none-any.whl
Collecting geventhttpclient
Downloading geventhttpclient-2.4.0-py3-none-any.whl
Installing collected packages: brotli, zope.interface, greenlet, gevent,
geventhttpclient, flask, flask-cors, flask-login, python-engineio,
python-socketio, pyzmq, msgpack, locust
Successfully installed locust-2.46.0 gevent-25.9.1 geventhttpclient-2.4.0 flask-3.1.3 requests-2.34.2
💡
pip install locust会同时装上它运行所需的依赖:gevent(协程并发库)、geventhttpclient(高性能 HTTP 客户端)、flask(Web UI)、requests、python-socketio等。
3.3 验证安装
/opt/data/locust/venv/bin/locust --version
/opt/data/locust/venv/bin/pip show locust
locust 2.46.0 from /opt/data/locust/venv/lib/python3.10/site-packages/locust (Python 3.10.12)
Name: locust
Version: 2.46.0
Summary: Developer-friendly load testing framework
Author: Jonatan Heyman, Lars Holmberg
License: MIT
Location: /opt/data/locust/venv/lib/python3.10/site-packages
Requires: configargparse, flask, flask-cors, flask-login, gevent, geventhttpclient, msgpack, psutil, pytest, python-engineio, python-socketio, pyzmq, requests, tomli, typing-extensions, werkzeug
Required-by:
⚠️
locust --version退出瞬间可能附带一行以Exception ignored开头、含greenlet is being finalized的提示,这是 gevent 与 Python 3.10 日志清理在进程退出时的竞态,进程 exit code 为 0,不影响版本信息,详见六、常见问题 6.3。
3.4 系统 pip 直装与镜像源(备用)
Ubuntu 22.04 的 pip3(22.0.2)默认不会触发 externally-managed 限制,也可直装到用户目录(仅当前用户可用):
pip3 install --user locust
内网/境内网络访问 PyPI 官方源较慢时,可用镜像源安装(清华 TUNA,与官方包内容一致):
/opt/data/locust/venv/bin/pip install -i https://pypi.tuna.tsinghua.edu.cn/simple locust
💡 若报错提示 pip 版本过旧,先在虚拟环境内升级 pip:
/opt/data/locust/venv/bin/pip install --upgrade pip。
3.5 卸载
删除整个虚拟环境即可彻底卸载 locust 及全部依赖:
rm -rf /opt/data/locust/venv
四、命令实测
实测约定:目标为 http://172.26.0.2:8080/(HTTP 服务,返回 200 与 index.html 内容)。文中输出均为逐条真实回显;压测机上的 locust 通过 /opt/data/locust/venv/bin/locust 调用。
4.1 编写压测脚本 locustfile.py
locust 通过一个 Python 文件定义压测场景。新建可独立运行的 locustfile.py:
cat > /opt/data/locust/locustfile.py <<'EOF'
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 3)
@task
def index(self):
self.client.get("/")
EOF
- 第 1 行导入
HttpUser(模拟用户基类)、task(任务装饰器)、between(随机等待时间)。 wait_time = between(1, 3):每个用户两次任务之间的等待时间取 1~3 秒的随机值,用于模拟真实用户思考时间。@task装饰index方法:定义该用户会执行的任务,这里发送GET /请求。这是压测任务的入口,压测频率受-u(用户数)与wait_time共同决定。
💡 可用
locust -l列出文件里定义的所有 UserClass,供校验脚本是否被正确识别。
4.2 -H, --host 与 -f, --locustfile(headless 基础压测)
-H 指定压测目标主机,-f 指定脚本文件。下面把两者与 -u -r -t --headless 组合,跑一次完整无头压测:
/opt/data/locust/venv/bin/locust --headless -f /opt/data/locust/locustfile.py -H http://172.26.0.2:8080 -u 5 -r 2 -t 8s
[2026-10-09 07:02:35,715] ubuntu-loadtester/INFO/locust.main: Starting Locust 2.46.0
[2026-10-09 07:02:35,716] ubuntu-loadtester/INFO/locust.main: Run time limit set to 8 seconds
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 0 0(0.00%) | 0 0 0 0 | 0.00 0.00
[2026-10-09 07:02:35,717] ubuntu-loadtester/INFO/locust.runners: Ramping to 5 users at a rate of 2.00 per second
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 6 0(0.00%) | 5 3 11 5 | 0.00 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 6 0(0.00%) | 5 3 11 5 | 0.00 0.00
[2026-10-09 07:02:37,719] ubuntu-loadtester/INFO/locust.runners: All users spawned: {"WebsiteUser": 5} (5 total users)
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 10 0(0.00%) | 4 3 11 3 | 2.00 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 10 0(0.00%) | 4 3 11 3 | 2.00 0.00
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 14 0(0.00%) | 4 3 11 3 | 2.00 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 14 0(0.00%) | 4 3 11 3 | 2.00 0.00
[2026-10-09 07:02:43,447] ubuntu-loadtester/INFO/locust.main: --run-time limit reached, shutting down
[2026-10-09 07:02:43,489] ubuntu-loadtester/INFO/locust.main: Shutting down (exit code 0)
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 19 0(0.00%) | 4 3 11 3 | 2.55 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 19 0(0.00%) | 4 3 11 3 | 2.55 0.00
Response time percentiles (approximated)
Type Name 50% 66% 75% 80% 90% 95% 98% 99% 99.9% 99.99% 100% # reqs
--------||--------|------|------|------|------|------|------|------|------|------|------|------
GET / 3 3 4 5 7 11 11 11 11 11 11 19
--------||--------|------|------|------|------|------|------|------|------|------|------|------
Aggregated 3 3 4 5 7 11 11 11 11 11 11 19
解读:
Starting Locust 2.46.0与Run time limit set to 8 seconds:-t 8s生效;Ramping to 5 users at a rate of 2.00 per second:-u 5、-r 2生效,每秒生成 2 个用户,约 2.5 秒铺满 5 个用户。- 表头
Type / Name / # reqs / # fails / Avg / Min / Max / Med / req/s / failures/s是 locust 的实时统计表:GET /表示该行是对GET /这个请求的统计;# reqs为已发请求数,# fails为失败数,Avg/Min/Max/Med是响应时间(毫秒),req/s为吞吐。 All users spawned: {"WebsiteUser": 5}:5 个模拟用户全部生成完成。- 最后一行汇总
Aggregated为全量结果:共 19 次请求、0 失败,QPS 2.55,中位延迟 3ms。 - 结束时打印
Response time percentiles:P50=3ms、P90=7ms、P99=11ms,用于评估延迟长尾。 - 因为
wait_time = between(1, 3),每个用户每 1~3 秒才发一次请求,所以 5 个用户在 8 秒内约发了 19 次请求、吞吐约 2.55 QPS——这与 wrk 的全连接高并发模型不同,属软件定义用户的正常表现。
4.3 -u, --users <N> 并发用户数
用途:指定峰值模拟用户数,主要与 --headless 配合使用。用户数越大,每秒产生的请求越多(乘以每个用户的平均发请求频率)。
/opt/data/locust/venv/bin/locust --headless -f /opt/data/locust/locustfile.py -H http://172.26.0.2:8080 -u 10 -r 2 -t 6s
[2026-10-09 07:02:58,230] ubuntu-loadtester/INFO/locust.main: Shutting down (exit code 0)
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 24 0(0.00%) | 4 3 10 4 | 4.27 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 24 0(0.00%) | 4 3 10 4 | 4.27 0.00
Response time percentiles (approximated)
Type Name 50% 66% 75% 80% 90% 95% 98% 99% 99.9% 99.99% 100% # reqs
--------||--------|------|------|------|------|------|------|------|------|------|------|------
GET / 4 4 5 5 5 5 10 10 10 10 10 24
--------||--------|------|------|------|------|------|------|------|------|------|------|------
Aggregated 4 4 5 5 5 5 10 10 10 10 10 24
解读:把用户数从 5 提到 10 后,6 秒内总请求数从约 19 升到 24,QPS 从 2.55 升到 4.27,约为原来的两倍(10 用户 × 平均约 0.5 次/秒 = 5 QPS 量级)。中位延迟仍为 4ms,说明该量级下服务稳定、无排队。实际压测时 -u 应结合目标服务的容量逐步上调,观察 QPS 与延迟的拐点。
4.4 -r, --spawn-rate <N> 用户生成速率
用途:指定每秒生成用户的速率(用户/秒),即 ramp-up 的快慢。速率越高,达到 -u 目标用户数越快。下面是 -u 20 -r 10(每秒铺 10 个用户):
/opt/data/locust/venv/bin/locust --headless -f /opt/data/locust/locustfile.py -H http://172.26.0.2:8080 -u 20 -r 10 -t 6s
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 62 0(0.00%) | 56 2 1050 4 | 10.83 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 62 0(0.00%) | 56 2 1050 4 | 10.83 0.00
Response time percentiles (approximated)
Type Name 50% 66% 75% 80% 90% 95% 98% 99% 99.9% 99.99% 100% # reqs
--------||--------|------|------|------|------|------|------|------|------|------|------|------
GET / 4 5 14 14 17 24 1000 1100 1100 1100 1100 62
--------||--------|------|------|------|------|------|------|------|------|------|------|------
Aggregated 4 5 14 14 17 24 1000 1100 1100 1100 1100 62
解读:-r 10 让 20 个用户在约 2 秒内全部铺满,起步阶段请求更密集。对比 4.3:QPS 升到 10.83,但同时 Max=1050ms、P98/P99 出现 1000/1100ms 长尾,说明秒级生成大量用户时,部分请求在 ramp-up 瞬时排队。-r 越小 ramp-up 越平缓,适合稳定压测;-r 越大越能制造突发流量,常用于测试瞬间并发压力。
4.5 -t, --run-time <T> 运行时长
用途:指定压测总时长,支持 300s、20m、3h、1h30m 等格式,只对 --headless/--autostart 生效。不带 -t 会一直运行直到手动终止(如 Ctrl+C)。
以 4.2 的基础命令为例,时长相关的关键回显为(中间 Ramping 与逐秒统计表部分略去):
[2026-10-09 07:02:35,716] ubuntu-loadtester/INFO/locust.main: Run time limit set to 8 seconds
[2026-10-09 07:02:43,447] ubuntu-loadtester/INFO/locust.main: --run-time limit reached, shutting down
[2026-10-09 07:02:43,489] ubuntu-loadtester/INFO/locust.main: Shutting down (exit code 0)
解读:启动时打印 Run time limit set to 8 seconds(-t 8s 生效);到点打印 --run-time limit reached, shutting down 后自动退出(exit code 0)。生产压测建议 -t 至少 10s~60s,太短的时长采样波动大、结果不可靠。
4.6 --headless 无头模式
用途:禁用 Web 界面,进程启动后立即开始压测,结果直接打印到终端(即 4.2~4.5 演示的运行方式),适合命令行/CI 一键运行。与它相对的是默认的 Web 模式(见 4.7)。
/opt/data/locust/venv/bin/locust --headless -f /opt/data/locust/locustfile.py -H http://172.26.0.2:8080 -u 5 -r 2 -t 8s
解读:--headless 必须与 -u(用户数)和 -t(时长)搭配使用才会自动启停并定时退出;单独 locust --headless 而不给 -u 会因缺少用户数而报错。无特别需要时,用 --headless + --csv 即可把压测结果落盘,供 CI 或脚本解析。若需要「边压测边看 Web 界面」,则去掉 --headless(用 --autostart)进入 Web 模式,见 4.7。
4.7 --web-port 8089 与 -P <端口> Web 界面端口
用途:locust 默认以 Web 模式启动,内置一个基于 Flask 的图形界面用于动态控制用户数、实时观察统计。--web-port <端口>(短选项 -P <端口>)指定 Web 界面监听端口,默认 8089。
/opt/data/locust/venv/bin/locust -f /opt/data/locust/locustfile.py -H http://172.26.0.2:8080 -u 5 -r 2 --web-port 8089
[2026-10-09 07:03:17,202] ubuntu-loadtester/INFO/locust.main: Starting Locust 2.46.0
[2026-10-09 07:03:17,203] ubuntu-loadtester/INFO/locust.main: Starting web interface at http://0.0.0.0:8089, press enter to open your default browser.
解读:Starting web interface at http://0.0.0.0:8089 表示 Web 界面已绑定在 8089 端口(--web-port 8089,等同 -P 8089)。此时进程持续运行等待 Web 界面下发「Start」指令,可用浏览器访问该地址手动控制压测开始/停止/调整用户数;无界面/脚本环境下请改用 --headless。多实例并列时用不同 --web-port 避免端口冲突。
4.8 --csv <前缀> 结果导出
用途:把统计结果以 CSV 落盘,用于后续绘图或用 pandas/Excel 分析。--csv <前缀> 会生成四个文件:<前缀>_stats.csv、<前缀>_stats_history.csv、<前缀>_failures.csv、<前缀>_exceptions.csv。
/opt/data/locust/venv/bin/locust --headless -f /opt/data/locust/locustfile.py -H http://172.26.0.2:8080 -u 5 -r 2 -t 8s --csv /opt/data/locust/result
运行后生成的文件:
-rw-r--r-- 1 root root 31 Oct 9 06:50 /opt/data/locust/result_exceptions.csv
-rw-r--r-- 1 root root 52 Oct 9 06:50 /opt/data/locust/result_failures.csv
-rw-r--r-- 1 root root 497 Oct 9 06:50 /opt/data/locust/result_stats.csv
-rw-r--r-- 1 root root 1127 Oct 9 06:50 /opt/data/locust/result_stats_history.csv
重点看 result_stats.csv(按请求维度的汇总),首行为表头,随后一行是一个请求的统计:
Type,Name,Request Count,Failure Count,Median Response Time,Average Response Time,Min Response Time,Max Response Time,Average Content Size,Requests/s,Failures/s,50%,66%,75%,80%,90%,95%,98%,99%,99.9%,99.99%,100%
GET,/,16,0,3.060292001464404,4.078360312632867,3.060292001464404,10.443085000588326,26.0,2.750321685708933,0.0,3,4,5,5,5,10,10,10,10,10,10
解读:result_stats.csv 每行对应一个请求维度,列含请求总数、失败数、中位/平均/最小/最大响应时间、平均响应体大小、Requests/s 和各百分位延迟;result_stats_history.csv 为带时间戳的历史采样;result_failures.csv、result_exceptions.csv 记录失败与异常(本测无失败,故几乎为空)。缺省不传 --csv 则仅打印终端统计,不落盘。
4.9 --loglevel <级别> 日志级别
用途:控制 locust 自身日志的输出粒度,可选 DEBUG/INFO/WARNING/ERROR/CRITICAL,默认 INFO。--loglevel WARNING(等价 -L WARNING)会屏蔽 INFO 级启动/铺用户日志,只保留统计表与告警。
/opt/data/locust/venv/bin/locust --headless -f /opt/data/locust/locustfile.py -H http://172.26.0.2:8080 -u 5 -r 2 -t 8s --loglevel WARNING
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 6 0(0.00%) | 5 3 11 5 | 0.00 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 6 0(0.00%) | 5 3 11 5 | 0.00 0.00
解读:对比 4.2 可明显看到,加上 --loglevel WARNING 后不再打印 Starting Locust、Ramping to、All users spawned、Run time limit set to 等 INFO 日志,只剩统计表。适合在输出要接入日志系统、只想要统计结果时使用。
五、帮助输出
5.1 locust --help(帮助全文)
/opt/data/locust/venv/bin/locust --help
Usage: locust [options] [UserClass ...]
Common options:
-h, --help show this help message and exit
-f <filename>, --locustfile <filename>
The Python file or module that contains your test,
e.g. 'my_test.py'. Accepts multiple comma-separated
.py files, a package name/directory or a url to a
remote locustfile. Defaults to 'locustfile.py'.
--config <filename> File to read additional configuration from. See https:
//docs.locust.io/en/stable/configuration.html#configur
ation-file
-H <base url>, --host <base url>
Host to load test, in the following format:
https://www.example.com
-u <int>, --users <int>
Peak number of concurrent Locust users. Primarily used
together with --headless or --autostart. Can be
changed during a test by keyboard inputs w, W (spawn
1, 10 users) and s, S (stop 1, 10 users)
-r <float>, --spawn-rate <float>
Rate to spawn users at (users per second). Primarily
used together with --headless or --autostart
-t <time string>, --run-time <time string>
Stop after the specified amount of time, e.g. (300s,
20m, 3h, 1h30m, etc.). Only used together with
--headless or --autostart. Defaults to run forever.
-l, --list Show list of possible User classes and exit
--config-users [CONFIG_USERS ...]
User configuration as a JSON string or file. A list of
arguments or an Array of JSON configuration may be
provided
Web UI options:
--web-host <ip> Host to bind the web interface to. Defaults to '*'
(all interfaces)
--web-port <port number>, -P <port number>
Port on which to run web host
--headless Disable the web interface, and start the test
immediately. Use -u and -t to control user count and
run time
--autostart Starts the test immediately (like --headless, but
without disabling the web UI)
--autoquit <seconds> Quits Locust entirely, X seconds after the run is
finished. Only used together with --autostart. The
default is to keep Locust running until you shut it
down using CTRL+C
--web-login Protects the web interface with a login page. See
https://docs.locust.io/en/stable/extending-
locust.html#authentication
--tls-cert <filename>
Optional path to TLS certificate to use to serve over
HTTPS
--tls-key <filename> Optional path to TLS private key to use to serve over
HTTPS
--class-picker Enable select boxes in the web interface to choose
from all available User classes and Shape classes
--web-base-path WEB_BASE_PATH
Base path for the web interface (e.g., '/locust').
Default is empty (root path).
Master options:
Options for running a Locust Master node when running Locust distributed. A Master node need Worker nodes that connect to it before it can run load tests.
--master Launch locust as a master node, to which worker nodes
connect.
--master-bind-host <ip>
IP address for the master to listen on, e.g
'192.168.1.1'. Defaults to * (all available
interfaces).
--master-bind-port <port number>
Port for the master to listen on. Defaults to 5557.
--expect-workers <int>
Delay starting the test until this number of workers
have connected (only used in combination with
--headless/--autostart).
--expect-workers-max-wait <int>
How long should the master wait for workers to connect
before giving up. Defaults to wait forever
--enable-rebalancing Re-distribute users if new workers are added or
removed during a test run. Experimental.
Worker options:
Options for running a Locust Worker node when running Locust distributed.
Typically ONLY these options (and --locustfile) need to be specified on workers, since other options (-u, -r, -t, ...) are controlled by the master node.
--worker Set locust to run in distributed mode with this
process as worker. Can be combined with setting
--locustfile to '-' to download it from master.
--processes <int> Number of times to fork the locust process, to enable
using system. Combine with --worker flag or let it
automatically set --worker and --master flags for an
all-in-one-solution. Not available on Windows.
Experimental.
--master-host <hostname>
Hostname of locust master node to connect to. Defaults
to 127.0.0.1.
--master-port <port number>
Port to connect to on master node. Defaults to 5557.
Tag options:
Locust tasks can be tagged using the @tag decorator. These options let specify which tasks to include or exclude during a test.
-T [<tag> ...], --tags [<tag> ...]
List of tags to include in the test, so only tasks
with at least one matching tag will be executed
-E [<tag> ...], --exclude-tags [<tag> ...]
List of tags to exclude from the test, so only tasks
with no matching tags will be executed
Request statistics options:
--csv <filename> Store request stats to files in CSV format. Setting
this option will generate three files:
<filename>_stats.csv, <filename>_stats_history.csv and
<filename>_failures.csv. Any folders part of the
prefix will be automatically created
--csv-full-history Store each stats entry in CSV format to
_stats_history.csv file. You must also specify the '--
csv' argument to enable this.
--print-stats Enable periodic printing of request stats in UI runs
--only-summary Disable periodic printing of request stats during
--headless run
--reset-stats Reset statistics once spawning has been completed.
Should be set on both master and workers when running
in distributed mode
--html <filename> Store HTML report to file path specified. Able to
parse certain tags - {u}, {r}, {t} and convert them to
number of users, spawn rate and run time respectively.
--json Prints the final stats in JSON format to stdout.
Useful for parsing the results in other
programs/scripts. Use together with --headless and
--skip-log for an output only with the json data.
--json-file <filename>
Prints the final stats in JSON format to file path
specified.
Logging options:
--skip-log-setup Disable Locust's logging setup. Instead, the
configuration is provided by the Locust test or Python
defaults.
--loglevel <level>, -L <level>
Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL.
Default is INFO.
--logfile <filename> Path to log file. If not set, log will go to stderr
Other options:
--show-task-ratio Print table of the User classes' task execution ratio.
Use this with non-zero --user option if some classes
define non-zero fixed_count attribute.
--show-task-ratio-json
Print json data of the User classes' task execution
ratio. Use this with non-zero --user option if some
classes define non-zero fixed_count attribute.
--version, -V Show program's version number and exit
--exit-code-on-error <int>
Sets the process exit code to use when a test result
contain any failure or error. Defaults to 1.
-s <number>, --stop-timeout <number>
Number of seconds to wait for a simulated user to
complete any executing task before exiting. Default is
to terminate immediately. When running distributed,
this only needs to be specified on the master.
--equal-weights Use equally distributed task weights, overriding the
weights specified in the locustfile.
--profile PROFILE Set a profile to group the testruns together
--otel Instrument the Locust test run with OpenTelemetry.
User classes:
<UserClass1 UserClass2>
At the end of the command line, you can list User
classes to be used (available User classes can be
listed with --list). LOCUST_USER_CLASSES environment
variable can also be used to specify User classes.
Default is to use all available User classes
Examples:
locust -f my_test.py -H https://www.example.com
locust --headless -u 100 -t 20m --processes 4 MyHttpUser AnotherUser
locust --headless -u 100 -r 10 -t 50 --print-stats --html "test_report_{u}_{r}_{t}.html"
(The above run would generate an html file with the name "test_report_100_10_50.html")
See documentation for more details, including how to set options using a file or environment variables: https://docs.locust.io/en/stable/configuration.html
💡 帮助里值得注意的默认值:
-f默认locustfile.py;--web-port/-P默认 8089;-t默认一直运行;--master-port/--master-bind-port默认 5557、--master-bind-host默认*;--loglevel/-L默认INFO;--exit-code-on-error默认 1。--tls-cert/--tls-key可用于 HTTPS 的 Web 界面。退出时末尾可能附带一行greenlet is being finalized提示,见 6.3。
5.2 版本查询
/opt/data/locust/venv/bin/locust --version
/opt/data/locust/venv/bin/pip show locust
locust 2.46.0 from /opt/data/locust/venv/lib/python3.10/site-packages/locust (Python 3.10.12)
Name: locust
Version: 2.46.0
Summary: Developer-friendly load testing framework
Location: /opt/data/locust/venv/lib/python3.10/site-packages
💡 两处都显示版本
2.46.0:locust --version打印运行实例版本与安装路径,pip show locust的Version字段同样表明 2.46.0。当前为 Python 3.10.12。
六、常见问题
6.1 pip3 install 报 externally-managed-environment
Q:执行 pip3 install locust 时报 error: externally-managed-environment,无法用系统 pip 安装?
A:该错误来自 PEP 668,常见于 Ubuntu 23.04 及以上把系统 Python 标记为「外部托管」,禁止 pip 直接写系统目录。Ubuntu 22.04(本文环境)默认不触发,若读者用的新版系统遇到,最简方案就是用虚拟环境隔离安装,与本文 3.2 一致:
python3 -m venv /opt/data/locust/venv
/opt/data/locust/venv/bin/pip install locust
⚠️ 不要把系统 Python 的 externally-managed 限制强行解除(如删除标记文件)来直装,容易破坏系统包;优先用虚拟环境或
pipx。
6.2 --log-level 提示 unrecognized arguments
Q:--log-level DEBUG 报 locust: error: unrecognized arguments: --log-level?
A:locust 的参数是单字 --loglevel(短选项 -L),不是 --log-level。拼错会直接打印错误并退出:
locust: error: unrecognized arguments: --log-level
Did you mean '--loglevel'?
改为 --loglevel DEBUG / --loglevel WARNING 即可。
6.3 locust --version/--help 伴随后 greenlet is being finalized
Q:运行 locust --version 或 --help 后出现以 Exception ignored 开头、含 greenlet is being finalized 的一长串报错?
A:这是 gevent 与 Python 3.10 在进程快速退出时日志清理模块与 greenlet 终结的竞态(RuntimeError: greenlet is being finalized),属良性、非功能性错误:进程 exit code 仍为 0,版本/帮助信息完整正确,headless 压测也不受影响。若在意输出整洁,可加 --loglevel WARNING 或忽略该行。
6.4 No module named locust 或 locust: command not found
Q:在虚拟环境 pip 里装了 locust,但 locust 命令找不到?
A:当前 shell 没激活虚拟环境,或 PATH 里没有 venv 的 bin。用虚拟环境内全路径调用即可:
/opt/data/locust/venv/bin/locust --version
或先激活环境再用短命令:
source /opt/data/locust/venv/bin/activate
locust --version
6.5 目标服务未启动时报 Connection refused
Q:压测时报错无法连接目标地址(如 http://172.26.0.2:8080)?
A:目标端口没有 HTTP 服务监听。locust 必须能对目标建立 TCP 并收到 HTTP 响应。若只需一个测试目标,可在目标机上起一个简单 HTTP 服务:
python3 -m http.server 8080 --bind 0.0.0.0
💡
python3 -m http.server会以服务根目录为站点根,返回 200 与目录/文件内容;生产压测请指向真实业务接口。
6.6 Web 界面能访问但压测不自动开始
Q:用 Web 模式(不加 --headless)启动后,浏览器打开 http://<IP>:8089 却在等待、没有流量?
A:正常现象。Web 模式下 locust 启动后进入「等待用户点击 Start」状态,需在 Web 界面上点 Start(输入用户数与生成速率)才会发起压测。若想启动即开始压测又保留 Web 界面,用 --autostart;若不要界面,用 --headless。
6.7 -u 很大但 req/s 并不高
Q:-u 500 压测但每秒请求数还是很低?
A:因为脚本里 wait_time = between(1, 3) 给每个用户加了 1~3 秒思考时间,起决定作用的是「用户数 ÷ 平均等待时间」,而非简单的用户数。要提高吞吐,可缩短/去掉 wait_time(如 wait_time = between(0, 1) 甚至设为 0),再配合 -r 快速铺用户。
七、参考链接
- locust 官方文档:https://docs.locust.io/
- locust 命令行参数配置说明:https://docs.locust.io/en/stable/configuration.html
- Python 官方虚拟环境 venv 说明:https://docs.python.org/3/library/venv.html
- 本文素材来源:Ubuntu 22.04 实测采集(locust 2.46.0,虚拟环境
/opt/data/locust/venv,目标 HTTP 服务 8080)