Python 参数解析 : Too few arguments

标签 python argparse

我正在尝试使用 Python 中的 argparse 库。我想让用户做类似的事情:

python my_script.py csv_name.csv [--dryrun]

其中 --dryrun 是可选参数。

然后我让用户输入 API key 和 key 。当我运行我的代码时,我不再输入 API 和 key ,然后我得到:

usage: my_script.py [-h] csv dryrun
salesforceImporter.py: error: too few arguments

这是我的代码:

def main():
    api_key = getpass.getpass(prompt='Enter API Key: ')
    secret_key = getpass.getpass(prompt='Enter Secret Key: ')

    parser = argparse.ArgumentParser()
    parser.add_argument("csv")
    parser.add_argument("dryrun")
    args = parser.parse_args()

    validate_csv_name(args.csv)

    is_dry_run = args.dryrun == '--dryrun'

知道我哪里出错了吗?

谢谢!

最佳答案

当您使用以下语法时:

parser.add_argument("csv")
parser.add_argument("dryrun")

您将这些添加为位置参数——必需——参数。只有前导破折号或两个破折号的参数是可选的。

参见 the docs here :

The add_argument() method must know whether an optional argument, like -f or --foo, or a positional argument, like a list of filenames, is expected. The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name. For example, an optional argument could be created like:

>>> parser.add_argument('-f', '--foo')

关于Python 参数解析 : Too few arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37869616/

相关文章:

python - 在一个图中叠加两个密度

python - python argparse 的 common-lisp 类似物是什么?

default - argparse默认选项基于另一个选项

python - Rosalind 共识和简介 python

python - 在python中解析csv字符串

python - 允许带有 nargs 的位置命令行参数由标志分隔

python - 如何使用 argparse 获得不带连字符 (--) 的可能参数列表

python - python中的n-gram,四,五,六克?

python - 覆盖率和分析器的组合?