简体   繁体   English

Python-可选命令行参数

[英]Python - Optional Command Line Argument

I would like to have an option -n, that will allow users to specify a size of a list. 我想有一个选项-n,它将允许用户指定列表的大小。 The default will be 30. So: 默认值为30。因此:

./findNumberOfPlayers.py -n10

I haven't done any command line arguments with python before but am confused with how to include -n10 within the program. 我之前没有用python做过任何命令行参数,但是对如何在程序中包含-n10感到困惑。 I understand I would import sys and have 12 assigned to sys.argv[1] but how does it work with -n10 ? 我知道我会import sys并将12分配给sys.argv[1]但它如何与-n10一起-n10

Thank You! 谢谢! I appreciate the help. 感谢您的帮助。

Use argparse . 使用argparse

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", help="Enter a number", type=int)

You can then access the arg like this - 然后,您可以像这样访问arg-

args = parser.parse_args()
num_players = args.number if args.number else 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM