简体   繁体   English

python 中的 -n 代表什么?

[英]What does -n in python represent?

import argparse

parser = argparse.ArgumentParser(description="Meow like a cat")
parser.add_argument("-n", default=1,help="number of times to meow", type=int)
args = parser.parse_args()

for _ in range(arg.n):
    print("meow")

I don't really understand the purpose of having -n in line 4, I know it's a value holder for command line argument, but why -n;我真的不明白在第 4 行中有 -n 的目的,我知道它是命令行参数的值持有者,但为什么 -n; is there a special meaning to it?它有什么特殊含义吗? Also, why in the for loop, the parameter takes arg.n instead of arg.-n since that's what it used before?另外,为什么在 for 循环中,参数采用 arg.n 而不是 arg.-n ,因为这是它以前使用的? Thank You for helping!感谢您的帮助!

add_argument("-n", ...) defines an argument that takes '-n'` as a flag, and is used as with add_argument("-n", ...)定义了一个以'-n'`作为标志的参数,并与

$python your_script -n 1

argparse sets that value to the args object. argparse将该值设置为args object。

print(args)
Namespace(n=1)

which is then accessed as然后访问为

args.n

All that should be explained in the argparse docs.所有这些都应该在argparse文档中解释。

'n' is called the dest , and is derived from the add_argument option-string by stripping off the dash. 'n' 被称为dest ,它是通过剥离破折号从add_argument选项字符串派生的。

 add_argument('-n','--number', ...)

would set the dest to 'number', but accept eitherdest设置为“数字”,但接受

 myscript -n 1
 myscript --number 3

It's a convention of passing arguments to programs, not a Python thing per se.这是将 arguments 传递给程序的约定,而不是 Python 本身的事情。 So usually it's -{single-letter} or --{a word} .所以通常是-{single-letter}--{a word} So -n would be the same as --number in that case所以-n在这种情况下与--number相同

Command-line tools have two kinds of arguments: flags/options (denoted by either a single or double dash, in this case -n but could also be something like --version ) and positional arguments which are just data (for example a path).命令行工具有两种 arguments:标志/选项(由单破折号或双破折号表示,在本例中为-n但也可能类似于--version )和位置 arguments 只是数据(例如路径)。 You can find one explanation of them here .您可以在此处找到它们的一种解释。

You can find documentation on argparse on Python docs that showcases what kind of options you have for different types of arguments and how they are translated into the resulting Python object. You can find documentation on argparse on Python docs that showcases what kind of options you have for different types of arguments and how they are translated into the resulting Python object.

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

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