簡體   English   中英

帶有1或3個位置參數的python腳本

[英]python script with 1 or 3 positional arguments

我正在編寫一個python腳本,它需要3個位置參數(名稱,日期,位置,讓我們說)或1個參數,這是一個包含該信息的安裝文件。

我知道我可以使用argparse ,我可以使位置參數可選:

parser.add_argument('name_OR_setupFile')
parser.add_argument('date', nargs='?')
parser.add_argument('location', nargs='?')

然后我可以進行錯誤檢查,以確保用戶沒有做任何愚蠢的事情

問題是現在幫助信息會非常混亂,因為不清楚第一個參數到底是什么。 我想用兩種不同的add_argument行來做這個,不知何故,但是我不確定如何。

我也知道我可以使用--setupFile參數,並使三個可選...但我不想那樣做,如果我不必。

第三種選擇是使用:

parser.add_argument('ARGS', nargs='+', help='ARGS is either of the form setupFile, or name date location')

然后再進行錯誤檢查......

ETA澄清:

我希望能夠用以下任一方式調用腳本:

python foo.py setupFile

要么

python foo.py name date location

我希望幫助文本是這樣的:

usage:
foo.py setupFile
foo.py name date location

我認為使用argparse的最清晰的設計是:

parser = argparse.ArgumentParser()
g = parser.add_mutually_exclusive_group()
g.add_argument('--setup','-s',metavar='FILE',help='your help')
g.add_argument('--name',nargs=3,metavar=('NAME','DATE','LOCATION'),hel
     ...: p='your help')

parser.print_help()產生:

usage: ipython3 [-h] [--setup FILE | --name NAME DATE LOCATION]

optional arguments:
  -h, --help            show this help message and exit
  --setup FILE, -s FILE
                        your help
  --name NAME DATE LOCATION
                        your help

我用互斥optionals處理了1 or 3參數要求。 並使用metavar來增加參數的清晰度。 (正如最近的另一個問題所指出的, metavarpositionals metavar 。)

另一種選擇是使用subparsers 這仍然需要一個關鍵詞,如setupname ,只有輸入沒有-- subparsers的幫助結構是完全不同的。

不完全確定這是你的意思,但如果我理解正確的話:

if __name__ =='__main__':
    def dem_args(*args):
        if len(args) == 1:
            if os.path.isfile(args[0]):
                #go file
            else:
                #error regarding this being a bad filename or nonexistent file  
        elif len(args) == 3:
            #try to process / raise errors regarding name, date, location
        else:
            #error reg. wrong number of arguments, possible arguments are either this or that 

好的,這就是我目前正在做的事情。 我把它放在這里供人們評論,如果它最終有用,后代。

我實際上在這里解決了一個額外的問題。 問題實際上比我指定的要復雜一點。 因為實際上有3種方式來運行程序,我希望能夠有一個--help選項,只給我一種類型的詳細信息。 所以我想-h,-h 1和-h 2都做不同的事情。

我目前的代碼是:

import argparse

baseParser = argparse.ArgumentParser(add_help=False)
baseParser.add_argument('-f', '--foo', help ='foo argument')
baseParser.add_argument('-h', '--help', nargs='?' , const = 'all')

parser1 = argparse.ArgumentParser(parents = [baseParser], add_help=False)
parser1.add_argument('name', help='name argument (type 1)')
parser1.add_argument('date', help='date argument')
parser1.add_argument('location', help='location argument')

setupParser=argparse.ArgumentParser(parents = [baseParser],add_help=False)
setupParser.add_argument('setup', help='setup file')

parser2 = argparse.ArgumentParser(parents = [baseParser],add_help=False)
parser2.add_argument('name', help='name argument (type 2)')
parser2.add_argument('baa', help='sheep?')

realParser = argparse.ArgumentParser(parents=[baseParser], add_help=False)
realParser.add_argument('ARGS', nargs = '*', help = 'positional arguments')

args = realParser.parse_args()
if args.help:
    if args.help == 'all':
        print 'This product can be used in multiple ways:'
        print 'setup'
        setupParser.print_usage()
        print 'type1'
        parser1.print_usage()
        print'type2'
        parser2.print_usage()
        print 'use help [type] for more details'
    elif args.help=='setup':
        setupParser.print_help()
    elif args.help=='1':
        parser1.print_help()
    else:
        parser2.print_help()
    exit(0)
    #actually parse the args in args.ARGS, and work with that

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM