最可靠的方式是检查 pytest_xdist_worker 环境变量是否存在:import os; is_xdist_worker = 'pytest_xdist_worker' in os.environ,该变量由 xdist 在 worker 进程启动时注入,主进程不设置,轻量且准确。
pytest_xdist_worker 环境变量是否存在pytest-xdist 在每个工作进程(worker)启动时会注入 pytest_xdist_worker 环境变量,值为 worker 名称(如 gw0、gw1)。这是最轻量、最可靠的运行时检测方式:
import os is_xdist_worker = 'pytest_xdist_worker' in os.environ
is_xdist_worker == True 意味着当前确实在某个 xdist worker 进程中执行pytestconfig 获取 xdist 相关配置pytest 提供的 pytestconfig fixture 可以访问命令行参数和插件配置,适合在 fixture 或测试函数中做条件逻辑:
pytestconfig.getoption('numprocesses', default=None) 返回 -n 指定的进程数(如 4),若为 None 或 1,大概率未启用多进程模式pytestconfig.pluginmanager.hasplugin('xdist') 仅表示 xdist 插件已加载,不能说明当前是 worker 进
if pytestconfig.getoption('numprocesses', default=1) > 1 and 'pytest_xdist_worker' in os.environ:可较准确断定“正在 xdist 多进程模式下运行且处于 worker 中”os.cpu_count() 或进程名启发式判断有人尝试用 CPU 核心数或 psutil.Process().name() 推断是否为 xdist worker,这类做法不可靠:
os.cpu_count() 只反映硬件能力,与 pytest 是否启用 xdist 无关;用户可能用 -n 2 在 32 核机器上跑,也可能用 -n auto 但受限于资源实际只启 1 个 workerpython 或 pytest,和主进程无本质区别;不同平台、venv、启动方式下进程名差异大--boxed 模式下进程模型更复杂检测逻辑的位置会影响结果准确性:
os.environ 检查 —— 安全,因为 xdist worker 启动时已注入变量conftest.py 的 pytest_configure hook 中检查 —— 安全,hook 执行时环境已就绪pytestconfig —— 必须声明为 scope='session' 或更宽作用域,否则可能因 fixture 初始化顺序问题拿不到正确值__init__.py 或非 pytest 上下文(如单独运行脚本)里依赖此检测,会引发未定义行为pytest_xdist_worker,也不代表你可以安全地复用主进程里初始化过的对象。