为何直接运行.py脚本时argparse无法识别参数?如何修复?
问题描述
在Windows命令行中运行Python脚本有两种方式:
- 直接执行:
directories.py arg1 - 通过Python解释器执行:
python directories.py arg1
使用argparse处理命令行参数前,两种方式均能正常运行;但引入argparse后,直接运行脚本时argparse无法识别arg1,报错信息如下:
Directories.py usage: directories.py [-h] [-f FILE] directory directories.py: error: the following arguments are required: directory
而通过python directories.py arg1执行时,argparse可正常解析参数。
相关argparse代码如下:
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Get tree from single dir or dir list from file") parser.add_argument("directory", type=str, help="Get single directory") # Adding argument parser.add_argument("-f", "--file", help = "Get directories from a file") # Read arguments from command line args = parser.parse_args() main(args)
原因分析
问题出在Windows的Python文件关联机制上:当直接在命令行输入.py文件名执行时,系统默认的关联规则是用python.exe "%1"启动脚本——这里仅传递了脚本文件路径(%1),没有传递后续的命令行参数。argparse根本没收到arg1,因此会报错缺少必填的directory参数。
修复方案
方案1:修改系统Python文件关联(永久生效)
以管理员身份打开命令提示符,执行以下命令:
- 关联
.py文件类型:assoc .py=Python.File - 修改关联执行命令,使其传递所有参数:
例如Python安装在ftype Python.File="C:\你的Python安装路径\python.exe" "%1" %*C:\Python310时,命令为:
修改完成后,直接运行ftype Python.File="C:\Python310\python.exe" "%1" %*directories.py arg1即可正常传递参数。
方案2:创建批处理文件替代直接运行脚本
若不想修改系统关联,可在脚本同目录下创建directories.bat文件,内容如下:
@echo off python "%~dp0directories.py" %*
之后直接运行directories.bat arg1,批处理会自动将所有参数传递给Python脚本,argparse即可正常解析。
内容的提问来源于stack exchange,提问作者wgw
相关产品推荐
相关产品推荐

