簡體   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