gpt4 book ai didi

python - Argparse 中的异常

转载 作者:行者123 更新时间:2023-11-28 17:40:10 26 4
gpt4 key购买 nike

我有以下代码用于从文件中读取参数并使用 argparse 处理它们,但出现错误,这是为什么?

import argparse
from ConfigParser import ConfigParser
import shlex

parser = argparse.ArgumentParser(description='Short sample app',
fromfile_prefix_chars='@')

parser.add_argument('--abool', action="store_true", default=False)
parser.add_argument('--bunit', action="store", dest="bunit",type=int)
parser.add_argument('--cpath', action="store", dest="c", type=str)

print parser.parse_args(['@argparse_fromfile_prefix_chars.txt']) #name of the file is argparse_fromfile_prefix_chars.txt

错误:

usage: -c [-h] [--abool] [--bunit BUNIT] [--cpath C]
-c: error: unrecognized arguments: --bunit 289 --cpath /path/to/file.txt
To exit: use 'exit', 'quit', or Ctrl-D.

文件 argparse_fromfile_prefix_chars.txt 的内容

--abool
--bunit 289
--cpath /path/to/file.txt

最佳答案

argparse 期望来自文件的参数每行一个。这意味着整行是一个引用的论点。所以你当前的 args 文件被解释为

python a.py '--abool' '--bunit 289' '--cpath /path/to/file.txt'

导致错误。相反,您的 args 文件应该如下所示

--abool
--bunit
289
--cpath
/path/to/file.txt

关于python - Argparse 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25536581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com