python - 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 并且没关系。但是如何添加另一个参数并取决于他选择其他方法来执行?
解决方案
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()
推荐阅读
- reporting-services - 在数据集的第一行上方显示标题,switch 语句中的表达式 SSRS
- sql - 使用 JOIN 两个表的 SQLLite 更新语句
- amazon-web-services - 域转发拒绝在框架中显示“http://webhosting.luminate.com/forward.html”,因为它将“X-Frame-Options”设置为“sameorigin”
- angular - Angular 4 iframe无法隐藏iframe内的元素
- azure - 使用侦听权限连接到 Azure 服务总线会导致错误
- android - 以编程方式在android 7中卸载Android应用程序
- ubuntu - 为 Ubuntu 安装 RT Linux 补丁
- regex - 在 Sublime Text 中匹配多行正则表达式
- java - 手机开机自动启动服务
- hibernate - Entitymanager (JPA/Hibernate) 在所有列中返回 Null 值