CentOS 8 locust 安装与命令参数详解
在 CentOS 8 上通过 python39 虚拟环境安装 locust 2.34.0,并逐参数实测 -f/-H/-u/-r/-t/--headless/--web-port/-P/--csv/--loglevel/--help 的输入与回显,覆盖 HttpUser 脚本、Web UI、headless 压测与排障。
CentOS 8 locust 安装与命令参数详解
目标:在 CentOS 8 上用 Python 3.9 虚拟环境安装 locust 2.34.0,并逐参数实测
-f指定脚本、-H目标主机、-u用户数、-r生成速率、-t运行时长、--headless无头模式、--web-port/-PWeb 端口、--csv导出、--loglevel日志级别及--help。本文命令与输出均为 CentOS 8(locust 2.34.0,Python 3.9)实测回显。
一、环境信息
- 操作系统:CentOS Linux release 8.4.2105
- Python:系统默认
python3为 3.6.8(不够新),实际安装用python3.9(3.9.2) - pip:虚拟环境内先升到 26.0.1,再装 locust
- locust 版本:2.34.0(安装在 Python 3.9 虚拟环境
/opt/data/locust/venv) - 压测机主机名:
centos-loadtester,网卡 eth0,IP172.26.0.5/16 - 压力测试目标:
http://172.26.0.3: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)两种运行方式。本文在 CentOS 8 上安装 2.34.0 并逐参数实测。
⚠️ 注意:CentOS 8 官方仓库已退役,安装系统 Python 包需先把 dnf 源切到可用的镜像源(见 3.1)。另外 locust 2.34.0 要求 Python 3.9 及以上,CentOS 8 默认
python3是 3.6,需安装python39(见 3.2)再建虚拟环境。
三、安装
3.1 准备可用的 dnf 软件源
⚠️ 前置:CentOS 8 已于 2024-05-31 停止维护,默认的
mirrorlist.centos.org与vault.centos.org均已失效(dnf报Couldn't resolve host或 HTTP 403)。境内可用清华 TUNA 的centos-vault镜像,把仓库 baseurl 指到它后再dnf install。例如写一个/etc/yum.repos.d/CentOS-Vault.repo:
mkdir -p /etc/yum.repos.d.bak
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d.bak/
cat > /etc/yum.repos.d/CentOS-Vault.repo <<'EOF'
[baseos]
name=CentOS 8 BaseOS - TUNA
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos-vault/8.4.2105/BaseOS/x86_64/os/
gpgcheck=0
[appstream]
name=CentOS 8 AppStream - TUNA
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos-vault/8.4.2105/AppStream/x86_64/os/
gpgcheck=0
[powertools]
name=CentOS 8 PowerTools - TUNA
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos-vault/8.4.2105/PowerTools/x86_64/os/
gpgcheck=0
EOF
dnf clean all
dnf makecache
CentOS 8 AppStream - TUNA 763 kB/s | 9.6 MB 00:12
CentOS 8 PowerTools - TUNA 885 kB/s | 2.4 MB 00:02
Last metadata expiration check: 0:00:02 ago on Fri Oct 9 06:53:10 2026.
Metadata cache created.
3.2 安装 Python(python3 + python39,locust 需 Python 3.9+)
CentOS 8 默认 python3 是 3.6.8,无法安装现代 locust(其依赖 gevent 在 3.6 上编译失败,见 6.2)。先装 python3、python3-pip,再装 python39:
sudo dnf install -y python3 python3-pip
sudo dnf install -y python39-pip
python3 --version
python3.9 --version
Python 3.6.8
Python 3.9.2
💡
python3对应 3.6.8,供系统工具使用;python3.9(来自python39模块)是安装 locust 的目标解释器。务必用python3.9建虚拟环境,不要用python3。
3.3 安装编译依赖
locust 的核心依赖 gevent 在 CentOS 8 上无现成 wheel,需从源码编译,先装编译工具链:
sudo dnf install -y gcc make python39-devel libffi-devel
pkgconf-pkg-config-1.4.2-1.el8.x86_64
python39-devel-3.9.2-1.module_el8.4.0+720+bfbc1bcb.x86_64
Complete!
💡
gcc/make用于编译 gevent,python39-devel提供 Python 3.9 头文件,libffi-devel提供 cffi 需要的 libffi 头文件。缺任一都会导致pip install在gevent一步构建失败。
3.4 创建虚拟环境并安装 locust(推荐)
用 python3.9 建虚拟环境,升级 pip 后安装 locust:
mkdir -p /opt/data/locust
python3.9 -m venv /opt/data/locust/venv
/opt/data/locust/venv/bin/pip install --upgrade pip
/opt/data/locust/venv/bin/pip install locust
虚拟环境内 pip 初始版本(创建时)与升级后:
/opt/data/locust/venv/bin/pip --version
pip 20.2.4 from /opt/data/locust/venv/lib64/python3.9/site-packages/pip (python 3.9)
安装 locust 成功(末尾回显):
Successfully built gevent
Installing collected packages: brotli, zope.interface, zipp, urllib3, setuptools, importlib-metadata, tomli, click, certifi, blinker, zope.event, werkzeug, requests, jinja2, greenlet, gevent, geventhttpclient, flask, flask-cors, flask-login, locust
Successfully installed greenlet-3.2.5 gevent-26.7.0 geventhttpclient-2.4.0 locust-2.34.0 requests-2.32.5 urllib3-2.6.3 werkzeug-3.1.9
💡 本次实测定使其
gevent-26.7.0为源码编译(Successfully built gevent),故 3.3 的编译工具链必不可少。换用官方已提供 wheel 的平台则无需编译。
3.5 验证安装
/opt/data/locust/venv/bin/locust --version
/opt/data/locust/venv/bin/pip show locust
locust 2.34.0 from /opt/data/locust/venv/lib64/python3.9/site-packages/locust (Python 3.9.2)
Name: locust
Version: 2.34.0
Summary: Developer-friendly load testing framework
Location: /opt/data/locust/venv/lib64/python3.9/site-packages
Requires: configargparse, flask, flask-cors, flask-login, gevent, geventhttpclient, msgpack, psutil, pyzmq, requests, setuptools, tomli, typing-extensions, werkzeug
Required-by:
⚠️ 运行
locust子命令时,日志首行可能出现Python 3.9 support is deprecated and will be removed soon的 WARNING,这是 locust 对 Python 3.9 的官方提醒,功能不受影响,详见 6.4。
3.6 镜像源备用与卸载
内网/境内访问官方 PyPI 较慢时,可用清华 TUNA 镜像(与官方包一致):
/opt/data/locust/venv/bin/pip install -i https://pypi.tuna.tsinghua.edu.cn/simple locust
卸载:删除整个虚拟环境即可彻底卸载 locust 及全部依赖:
rm -rf /opt/data/locust/venv
四、命令实测
实测约定:目标为 http://172.26.0.3: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.3:8080 -u 5 -r 2 -t 8s
[2026-10-09 07:08:51,104] centos-loadtester/INFO/locust.main: Starting Locust 2.34.0
[2026-10-09 07:08:51,104] centos-loadtester/WARNING/locust.main: Python 3.9 support is deprecated and will be removed soon
[2026-10-09 07:08:51,104] centos-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:08:51,105] centos-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 / 5 0(0.00%) | 4 2 8 3 | 0.00 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 5 0(0.00%) | 4 2 8 3 | 0.00 0.00
[2026-10-09 07:08:53,108] centos-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%) | 3 2 8 3 | 2.00 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 10 0(0.00%) | 3 2 8 3 | 2.00 0.00
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 13 0(0.00%) | 3 2 8 3 | 2.33 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 13 0(0.00%) | 3 2 8 3 | 2.33 0.00
[2026-10-09 07:08:58,878] centos-loadtester/INFO/locust.main: --run-time limit reached, shutting down
[2026-10-09 07:08:58,929] centos-loadtester/INFO/locust.main: Shutting down (exit code 0)
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 18 0(0.00%) | 3 2 8 3 | 2.35 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 18 0(0.00%) | 3 2 8 3 | 2.35 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 3 3 4 9 9 9 9 9 9 18
--------||--------|------|------|------|------|------|------|------|------|------|------|------
Aggregated 3 3 3 3 4 9 9 9 9 9 9 18
解读:
- 首行
Starting Locust 2.34.0,随后一行 WARNINGPython 3.9 support is deprecated and will be removed soon(locust 对 Python 3.9 的提醒,不影响功能);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生效。 - 表头
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:共 18 次请求、0 失败,QPS 2.35,中位延迟 3ms。 - 结束时打印
Response time percentiles:P50=3ms、P90=4ms、P99=9ms,用于评估延迟长尾。 - 因
wait_time = between(1, 3),每个用户 1~3 秒才发一次请求,5 个用户 8 秒约发 18 次、QPS 约 2.35,属软件定义用户的正常表现,与 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.3:8080 -u 10 -r 2 -t 8s
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 33 0(0.00%) | 3 2 10 3 | 4.31 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 33 0(0.00%) | 3 2 10 3 | 4.31 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 3 4 4 5 10 10 10 10 10 33
--------||--------|------|------|------|------|------|------|------|------|------|------|------
Aggregated 3 3 3 4 4 5 10 10 10 10 10 33
解读:把用户数从 5 提到 10 后,8 秒内总请求数从 18 升到 33,QPS 从 2.35 升到 4.31(约两倍)。中位延迟仍为 3ms、无失败,说明该量级下服务稳定、无排队。实际压测应结合目标服务容量逐步上调 -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.3:8080 -u 20 -r 10 -t 8s
Type Name # reqs # fails | Avg Min Max Med | req/s failures/s
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
GET / 78 0(0.00%) | 83 2 1046 3 | 10.16 0.00
--------||-------|-------------|-------|-------|-------|-------|--------|-----------
Aggregated 78 0(0.00%) | 83 2 1046 3 | 10.16 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 9 10 12 1000 1000 1000 1000 1000 1000 78
--------||--------|------|------|------|------|------|------|------|------|------|------|------
Aggregated 3 3 9 10 12 1000 1000 1000 1000 1000 1000 78
解读:-r 10 让 20 个用户在约 2 秒内全部铺满,起步阶段请求更密集。对比 4.3:QPS 升到 10.16,同时 Max=1046ms、P98/P99 出现 1000~1100ms 长尾,说明秒级铺满 20 用户时部分请求在 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:08:51,104] centos-loadtester/INFO/locust.main: Run time limit set to 8 seconds
[2026-10-09 07:08:58,878] centos-loadtester/INFO/locust.main: --run-time limit reached, shutting down
[2026-10-09 07:08:58,929] centos-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.3: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.3:8080 -u 5 -r 2 --web-port 8089
[2026-10-09 07:03:34,164] centos-loadtester/INFO/locust.main: Starting Locust 2.34.0
[2026-10-09 07:03:34,165] centos-loadtester/WARNING/locust.main: Python 3.9 support is deprecated and will be removed soon
[2026-10-09 07:03:34,165] centos-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.3:8080 -u 10 -r 2 -t 6s --csv /opt/data/locust/result
运行后生成的文件:
/opt/data/locust/result_exceptions.csv
/opt/data/locust/result_failures.csv
/opt/data/locust/result_stats.csv
/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.3:8080 -u 10 -r 2 -t 6s --loglevel WARNING
Type Name 50% 66% 75% 80% 90% 95% 98% 99% 99.9% 99.99% 100% # reqs
--------||--------|------|------|------|------|------|------|------|------|------|------|------
GET / 3 3 3 3 4 4 9 9 9 9 9 24
--------||--------|------|------|------|------|------|------|------|------|------|------|------
Aggregated 3 3 3 3 4 4 9 9 9 9 9 24
解读:加上 --loglevel WARNING 后,不再打印 Starting Locust、Ramping to、All users spawned、Run time limit set to 等 INFO 日志,也不打印 Python 3.9 的 WARNING 以外的多余日志,只剩统计表与最终百分位。适合输出要接入日志系统、只想看统计结果时使用。
五、帮助输出
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'.
--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;--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 界面。
5.2 版本查询
/opt/data/locust/venv/bin/locust --version
/opt/data/locust/venv/bin/pip show locust
locust 2.34.0 from /opt/data/locust/venv/lib64/python3.9/site-packages/locust (Python 3.9.2)
Name: locust
Version: 2.34.0
Summary: Developer-friendly load testing framework
Location: /opt/data/locust/venv/lib64/python3.9/site-packages
💡 两处都显示版本
2.34.0:locust --version打印运行实例版本与安装路径,pip show locust的Version字段同样表明 2.34.0。当前为 Python 3.9.2。
六、常见问题
6.1 dnf install 报 Couldn't resolve host 或 HTTP 403
Q:dnf install 报 Couldn't resolve host name for http://mirrorlist.centos.org 或 HTTP 403?
A:CentOS 8 已停止维护,官方 mirrorlist.centos.org 与 vault.centos.org 均失效。按 3.1 把 /etc/yum.repos.d/ 的仓库 baseurl 指到清华 TUNA 的 centos-vault 镜像(https://mirrors.tuna.tsinghua.edu.cn/centos-vault/8.4.2105/{BaseOS,AppStream,PowerTools}/x86_64/os/)后重试。
6.2 用系统 python3(3.6)装 locust 失败
Q:python3 -m venv 建出的环境 pip install locust 在 gevent 一步报 command 'gcc' failed with exit status 1?
A:locust 2.34.0 要求 Python 3.9 及以上,CentOS 8 默认 python3 是 3.6.8,满足不了依赖(尤其 gevent)。请先按 3.2 安装 python39,再用 python3.9 -m venv 建虚拟环境安装,不要用 python3。
6.3 pip install locust 报 Failed to build wheel for gevent
Q:pip install locust 报 ERROR: Failed building wheel for gevent / failed to build wheel for gevent?
A:CentOS 8 上没有 gevent 的现成预编译 wheel,pip 改为源码编译,但缺编译工具与头文件而失败。按 3.3 安装 gcc make python39-devel libffi-devel 后重新 pip install locust 即可(实测装完后出现 Successfully built gevent)。
6.4 报 Python 3.9 support is deprecated and will be removed soon
Q:每次运行 locust 首行都出现 Python 3.9 support is deprecated and will be removed soon 的 WARNING?
A:这是 locust 对即将弃用 Python 3.9 的官方提醒。CentOS 8 官方只提供到 Python 3.9(python39),无法用更高版本,该警告不影响功能,可忽略;后续如需更高 Python,应迁移到更新的发行版。
6.5 --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.6 locust: command not found 或 No module named locust
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.7 目标服务未启动时报无法连接
Q:压测时报错无法连接目标地址(如 http://172.26.0.3:8080)?
A:目标端口没有 HTTP 服务监听。locust 必须能对目标建立 TCP 并收到 HTTP 响应。若只需一个测试目标,可在目标机上起一个简单 HTTP 服务:
python3 -m http.server 8080 --bind 0.0.0.0
💡
python3 -m http.server会以服务根目录为站点根,返回 200 与目录/文件内容;生产压测请指向真实业务接口。
6.8 -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
- 清华 TUNA 的 centos-vault 镜像(CentOS 8 停维后源):https://mirrors.tuna.tsinghua.edu.cn/centos-vault/
- Python 官方虚拟环境 venv 说明:https://docs.python.org/3/library/venv.html
- 本文素材来源:CentOS 8 实测采集(locust 2.34.0,Python 3.9 虚拟环境
/opt/data/locust/venv,目标 HTTP 服务 8080)