首页 > 解决方案 > Python 基于 argparse 选择方法

问题描述

我想根据 CLI 的参数执行不同的方法。我的main.py

from option import Option
import argparse

parser = argparse.ArgumentParser()
parser.add_argument( "--word", "-w", help="Find score for word", type=str)
args = parser.parse_args()

option = Option()
option.score_from_word(args.word)

Option.py

class Option():
    SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
                (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
    global LETTER_SCORES 
    LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
             for letter in letters.split()}

    def score_from_word(self,word):
        score = 0
        for w in word:
            if w in LETTER_SCORES.keys():
                score += LETTER_SCORES.get(w)
        print(score)

    def score_from_file(self):
        file = [line.rstrip('\n') for line in open('dictionary.txt', "r")]
        print(max(sum(LETTER_SCORES[c.upper()] for c in word) for word in file))

如果在命令行中我写: python -w KOT 它返回 7 并且没关系。但是如何添加另一个参数并取决于他选择其他方法来执行?

标签: pythoncommand-line-interfaceargparse

解决方案


Namespace只需添加另一个参数,并通过测试 args ( ) 属性来查找您所处的情况。

from option import Option
import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument( "--word", "-w", help="Find score for word", type=str)
group.add_argument( "--file", "-f", help="Find score for words in file", action='store_true')
args = parser.parse_args()

option = Option()
if args.word:
    option.score_from_word(args.word)
elif args.file:
    option.score_from_file()

推荐阅读