我创建了一个方法,将一个句子拆分成单词并返回句子的第一个单词(可以使用NLTK tokenizer
或argparse
,但由于这是一个用于学习Python的类项目,因此我从头开始创建了一个简单的标记器)该方法还有一个有用的“help”参数,其中传递-h
或--help
将显示帮助文本。但是,我希望函数输出帮助文本,如果用户通过-h或--help,则输出'break'或'pass'。我的方法是:
class example_method(object):
def __init__(self):
self.data = []
def parse(self, message):
if(("-h" or "--help") in message):
print("This is a helpful message")
else:
self.data = [x.strip() for x in message.split(' ')]
return self.data
如果用户输入一条常规消息,则该方法有效。让我举例说明:
example = example_method()
input_message = "Hello there how are you?"
print(example.parse(input_message)[0])
以上方法效果很好。但是,如果用户输入-h或--help,该方法将返回一个错误:
example = example_method()
input_message = "--help"
print(example.parse(input_message)[0])
以上将返回:TypeError: 'NoneType' object is not subscriptable
我意识到一个可能的解决方案是:
try: print(example.parse(input_message)[0])
except: pass
但是有没有一种方法可以像这样从方法内部返回pass
?你知道吗
def parse(self, message):
if(("-h" or "--help") in message):
print("This is a helpful message")
return pass
else:
self.data = [x.strip() for x in message.split(' ')]
return self.data
我的目的是,我不想要一个错误消息,因为这个方法是一个更大的程序的一部分,一个错误只会使输出看起来难看。如果该方法输出帮助文本,然后在没有错误的情况下退出,那么看起来会更加专业。你知道吗
也许只需要安排
parse
函数返回None
,然后调用函数就可以检查这种情况并处理它例如:
可以使用
exit()
立即停止程序执行。你知道吗考虑使用^{} 来自动生成
-h
和--help
标志和帮助文本。你知道吗低工作量演示:
你知道吗脚本.py你知道吗
用法:
如您所见,使用
-h
(或--help
)显示帮助消息,并且不执行任何其他代码(默认情况下)。你知道吗相关问题 更多 >
编程相关推荐