我试图通过 argparse 使用位置参数,但我无法访问这个参数值...我尝试查看 python 中关于 argparse 的文档,但我没有找到任何真正清晰的内容,也没有在不同的线程上找到任何内容。 。
这是我的代码:
parser = argparse.ArgumentParser(description='valid arguments')
parser.add_argument('file_liste', type=str, help='give a valid list')
args = parser.parse_args()
print(args)
Run Code Online (Sandbox Code Playgroud)
这是我得到的结果:
Namespace(file_liste='my_list.txt')
Run Code Online (Sandbox Code Playgroud)
这是我启动脚本的命令行:
python my_script.py my_list.txt
Run Code Online (Sandbox Code Playgroud)
我想要的是我的脚本采用 txt 文件作为参数来读取它,但我无法访问应存储在名为“file_liste”的变量中的值。
我尝试了这个,但出现错误:
print(args[0], "this is args[0]")
TypeError: 'Namespace' object does not support indexing
Run Code Online (Sandbox Code Playgroud)
这可能是一件愚蠢的事情,但我没有找到任何我能理解的答案......
args为您提供参数,正如错误所述,它不支持索引。它为您提供命名项目,例如,
args.file_liste
Run Code Online (Sandbox Code Playgroud)
将是您要求的文件列表。
| 归档时间: |
|
| 查看次数: |
2986 次 |
| 最近记录: |