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

sve*_*lar 5 python python-2.7 python-3.x

如何使用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"
Run Code Online (Sandbox Code Playgroud)

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

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


在BASH中,我可以在使用时完成此操作getopts.处理所有所需的开关,在的情况下环后,我有这样一行shift $((OPTIND-1)),并从那里我可以使用标准访问所有剩余的参数$1,$2,$3,等...
难道这样的事情exisit为argparse?

jed*_*rds 6

要获得您正在寻找的内容,诀窍是使用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])
Run Code Online (Sandbox Code Playgroud)

编辑:

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

./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])
Run Code Online (Sandbox Code Playgroud)

其中显示以下帮助信息:

./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"可选参数"下的帮助中添加了.