You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Make递归获取目录及子目录下的指定测试文件?

解决Makefile递归匹配测试文件的问题

方法1:启用bash的globstar特性

Make默认使用/bin/sh,而bash的globstar选项能让**匹配任意层级的子目录(包括当前目录本身)。修改Makefile如下:

# 指定用bash作为shell,开启globstar特性
SHELL := /bin/bash
.SHELLFLAGS := -O globstar -c

TESTS = dir_1/**/test_*.py dir_2/**/test_*.py

check_tests:
	set -x; for test_file in $(TESTS); do echo $$test_file; check_test $$test_file; done;

这样dir_1/**/test_*.py会匹配dir_1下所有层级(包括dir_1根目录)的test_*.py文件,dir_2同理,一次就能覆盖所有符合条件的文件。

方法2:用find命令生成文件列表

如果不想依赖bash特性,用find命令是更通用的跨环境方案:

# 递归查找指定目录下所有符合命名规则的测试文件
TESTS := $(shell find dir_1 dir_2 -name 'test_*.py')

check_tests:
	set -x; for test_file in $(TESTS); do echo $$test_file; check_test $$test_file; done;

find dir_1 dir_2 -name 'test_*.py'会自动遍历两个目录的所有子层级,把所有匹配的文件路径收集起来赋值给TESTS,兼容性拉满。

额外提示

如果需要排除某些特定子目录,给find加过滤参数就行,比如:

TESTS := $(shell find dir_1 dir_2 -name 'test_*.py' -not -path '*/temp_dir/*')

内容的提问来源于stack exchange,提问作者Ibolit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:35:27