我正在尝试使用 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/