Python 在 argparse 中带有破折号的选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12834785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Having options in argparse with a dash
提问by Cemre
I want to have some options in argparse module such as --pm-exporthowever when I try to use it like args.pm-exportI get the error that there is not attribute pm. How can I get around this issue? Is it possible to have -in command line options?
我想在 argparse 模块中有一些选项,例如--pm-export当我尝试使用它时,就像args.pm-export我收到没有属性的错误一样pm。我怎样才能解决这个问题?是否可以-在命令行选项中使用?
采纳答案by Thomas Orozco
As indicated in the argparsedocs:
For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial
--string. Any internal-characters will be converted to_charactersto make sure the string is a valid attribute name
对于可选参数操作,dest 的值通常是从选项字符串中推断出来的。ArgumentParser 通过获取第一个长选项字符串并剥离初始
--字符串来生成 dest 的值。任何内部-字符都将转换为_字符以确保字符串是有效的属性名称
So you should be using args.pm_export.
所以你应该使用args.pm_export.
回答by georg
Dashes are converted to underscores:
破折号转换为下划线:
import argparse
pa = argparse.ArgumentParser()
pa.add_argument('--foo-bar')
args = pa.parse_args(['--foo-bar', '24'])
print args # Namespace(foo_bar='24')
回答by seriyPS
Unfortunately, dash-to-underscore replacement doesn't work for positionalarguments (not prefixed by --) like
不幸的是,短划线到下划线替换不适用于位置参数(不以 为前缀--),例如
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('logs-dir',
help='Directory with .log and .log.gz files')
parser.add_argument('results-csv', type=argparse.FileType('w'),
default=sys.stdout,
help='Output .csv filename')
args = parser.parse_args()
print args
# gives
# Namespace(logs-dir='./', results-csv=<open file 'lool.csv', mode 'w' at 0x9020650>)
So, you should use 1'st argument to add_argument()as attribute name and metavarkwarg to set how it should look in help:
因此,您应该使用第一个参数add_argument()作为属性名称和metavarkwarg 来设置它在帮助中的外观:
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('logs_dir', metavar='logs-dir',
nargs=1,
help='Directory with .log and .log.gz files')
parser.add_argument('results_csv', metavar='results-csv',
nargs=1,
type=argparse.FileType('w'),
default=sys.stdout,
help='Output .csv filename')
args = parser.parse_args()
print args
# gives
# Namespace(logs_dir=['./'], results_csv=[<open file 'lool.csv', mode 'w' at 0xb71385f8>])

