繁体   English   中英

python - 使用argparse,传递一个任意字符串作为参数,以便在脚本中使用

[英]python - Using argparse, pass an arbitrary string as an argument to be used in the script

如何使用argparse将任意字符串定义为可选参数?

例:

[user@host]$ ./script.py FOOBAR -a -b
Running "script.py"...
You set the option "-a"
You set the option "-b"
You passed the string "FOOBAR"

理想情况下,我认为论点的立场无关紧要。 即:

./script.py -a FOOBAR -b == ./script.py -a -b FOOBAR == ./script.py FOOBAR -a -b


在BASH中,我可以在使用getopts完成此任务。 在处理case循环中的所有所需开关之后,我有一行读取shift $((OPTIND-1)) ,从那里我可以使用标准的$1$2$3等访问所有剩余的参数...
argparse有类似的东西吗?

要获得您正在寻找的内容,诀窍是使用parse_known_args()而不是parse_args()

#!/bin/env python 

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")

opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder (opts[1] is a list (possibly empty) of all remaining args)
if opts[1]: print('You passed the strings %s' % opts[1])

编辑:

以上代码显示以下帮助信息:

./clargs.py  -h

usage: clargs_old.py [-h] [-a] [-b]

optional arguments:
  -h, --help  show this help message and exit
  -a
  -b

如果你想告诉用户可选的任意参数,我能想到的唯一解决方案是继承ArgumentParser并自己编写。

例如:

#!/bin/env python 

import os
import argparse

class MyParser(argparse.ArgumentParser):
    def format_help(self):
        help = super(MyParser, self).format_help()
        helplines = help.splitlines()
        helplines[0] += ' [FOO]'
        helplines.append('  FOO         some description of FOO')
        helplines.append('')    # Just a trick to force a linesep at the end
        return os.linesep.join(helplines)

parser = MyParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")

opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder
if opts[1]: print('You passed the strings %s' % opts[1])

其中显示以下帮助信息:

./clargs.py -h

usage: clargs.py [-h] [-a] [-b] [FOO]

optional arguments:
  -h, --help  show this help message and exit
  -a
  -b
  FOO         some description of FOO

请注意在“使用”行中添加[FOO] ,在“可选参数”下添加帮助中的FOO

暂无
暂无

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

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