Windows环境下如何用Pylint扫描目录下所有非.py扩展名文件
解决Pylint在Windows下扫描非.py扩展名文件的通配符问题
问题背景
在Windows系统使用Python 3.9 + Pylint 2.16.1时,遇到以下情况:
- 单独扫描单个非.py扩展名文件(如
pylint my_file_name.abc)可正常输出结果 - 使用通配符
pylint *.abc扫描时,报错:
************* Module *.abc
*.abc:1:0: F0001: No module named *.abc (fatal)
- 运行目录已存在
__init__.py文件,需要扫描目录及其子目录中所有目标扩展名文件
原因分析
Windows命令行(尤其是CMD)不会自动将通配符*.abc展开为匹配的文件列表,而是直接把字符串*.abc传递给Pylint。Pylint会将其识别为Python模块名而非文件路径,因此触发"找不到模块"的致命错误。
解决方案
方法1:使用PowerShell遍历文件
利用PowerShell的文件遍历能力,将匹配的文件逐个传给Pylint:
Get-ChildItem -Recurse -Filter *.abc | ForEach-Object { pylint $_.FullName }
-Recurse:遍历当前目录及所有子目录-Filter *.abc:筛选出.abc扩展名的文件ForEach-Object:对每个匹配文件执行Pylint扫描
方法2:编写Python脚本批量扫描
如果需要更灵活的逻辑,可以写一个简单的Python脚本遍历目标文件并调用Pylint:
import os import subprocess def scan_target_files(root_dir, target_ext): for dirpath, _, filenames in os.walk(root_dir): for file in filenames: if file.endswith(target_ext): full_path = os.path.join(dirpath, file) subprocess.run(["pylint", full_path], shell=False) if __name__ == "__main__": # 扫描当前目录及子目录下所有.abc文件 scan_target_files(".", ".abc")
运行脚本即可自动完成批量扫描。
方法3:使用CMD的for循环
若习惯使用CMD命令行,可通过递归for循环实现:
for /r %f in (*.abc) do pylint "%f"
/r:递归遍历子目录%f:代表匹配到的文件路径
如果是在批处理(.bat)文件中执行,需将%f改为%%f:
for /r %%f in (*.abc) do pylint "%%f"
内容的提问来源于stack exchange,提问作者Piyush Aggarwal
相关产品推荐
相关产品推荐

