如何从函数或方法中返回“通过”?

时间:2019-01-03 11:50:45

标签: python methods

我创建了一种方法,该方法将句子拆分为单词并返回句子的第一个单词(您可以为此使用NLTK tokenizerargparse,但这是一个用于学习Python的类项目,我从头开始创建了一个简单的tokenizer)。该方法还具有一个有用的'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

我的目标是我不希望收到错误消息,因为此方法是较大程序的一部分,并且错误只会使输出看起来难看。如果该方法输出帮助文本然后退出而没有错误,则看起来会更加专业。

5 个答案:

答案 0 :(得分:2)

也许只是安排您的parse函数返回None,然后调用函数就可以检查这种情况并进行处理……

例如:

class example_method(object):
    # …
    def parse(self, message):
        if message in {"-h", "--help"}:
            print("This is a helpful message")
            return  # implicitly returns None

        self.data = [x.strip() for x in message.split(' ')]
        return self.data

res = example.parse(input_message)
if res is None:
    return

print(res[0])

答案 1 :(得分:1)

您可以使用module.exports = { mode: 'production', cache: false, entry: { index: ['babel-polyfill', './client/src/app.jsx'], }, optimization: { minimizer: [new TerserPlugin({ parallel: true, sourceMap: true, terserOptions: { mangle: true, safari10: true, compress: {}, warnings: false, ecma: 6, output: { comments: false, }, }, })], }, devtool: 'source-map', output: { path: `${rootPath}/server-dist/public/`, filename: '[name].[contenthash].bundle.js', chunkFilename: '[name].[contenthash].bundle.js', publicPath: '/', }, module: { rules: [ // compile js { test: /\.jsx?$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['react', 'es2015', 'stage-2'], plugins: ['react-hot-loader/babel', ['module-resolver', { alias: { common: './common', }, }]], babelrc: false, }, }, }, // compile sass { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'resolve-url-loader', 'postcss-loader?sourceMap', 'sass-loader?sourceMap', ], }, // load images { test: /\.(jpe?g|png|gif|svg)$/i, use: [ 'file-loader?hash=sha512&digest=hex&name=assets/img/[name].[ext]', { loader: 'image-webpack-loader', query: { mozjpeg: { progressive: true, }, gifsicle: { interlaced: true, }, optipng: { optimizationLevel: 7, }, }, }, ], }, // load fonts { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, use: 'file-loader?name=assets/fonts/[name].[ext]', }, { test: require.resolve('blueimp-file-upload'), loader: 'imports-loader?define=>false', }, { test: require.resolve('medium-editor-insert-plugin'), loader: 'imports-loader?define=>false', }, ], }, resolve: { extensions: ['.js', '.jsx'], alias: { 'jquery-ui/widget$': 'jquery-ui/ui/widget', }, }, plugins: [ new HtmlWebpackPlugin({ inject: true, template: `${rootPath}/client/index.html`, }), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.ProvidePlugin({ jQuery: 'jquery', $: 'jquery', jquery: 'jquery', }), new webpack.EnvironmentPlugin(['TEST']), extractSass, ], node: { dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty', }, }; 立即停止程序执行。

exit()

答案 2 :(得分:1)

考虑使用argparse来自动生成-h--help标志以及帮助文本。

省力的演示:

script.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-p', help='This will be printed')
args = parser.parse_args()

print(args.p)

用法:

$ python3 script.py -p hello
hello
$ python3 script.py -h
usage: script.py [-h] [-p P]

optional arguments:
  -h, --help  show this help message and exit
  -p P        This will be printed

如您所见,使用-h(或--help)显示帮助消息,并且不执行任何其他代码(默认情况下)。

答案 3 :(得分:0)

您应该考虑一下您的设计...添加

def help(self): 
    print("Cool description")

方法并从def parse(self, message)中删除“帮助开关解析”。

您正在削弱解析器的功能...考虑解析这个完全人为的消息:

"Paris is a cool town-however you travel it: by foot, by bike or by parachute." 

请参见SRP (Single responsibility principle)-parse不应打印帮助消息。


您还可以使用文档来提供help()

class well_documented_example_class(object):
    """Totally well documented class"""

    def parse(self, message):
        """This method does coool things with your 'message'

        'message' : a string with text in it to be parsed"""
        self.data = [x.strip() for x in message.split(' ')]
        return self.data

您可以通过以下方式获得帮助:

print(help(well_documented_example_class))

获得:

class well_documented_example_class(builtins.object)
 |  Totally well documented class
 |  
 |  Methods defined here:
 |  
 |  parse(self, message)
 |      This method does coool things with your 'message'
 |      
 |      'message' : a string with text in it to be parsed
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

答案 4 :(得分:0)

由于您的所有建议,我创建了自己的命令解析模块来解决此问题。您可以在GitHub上找到它:https://github.com/MonkeyBot2020/comparse

以下是其用法的一些示例:

from comparse import comparse
query = comparse(False)
query.add_argument("log_channel", "str", "logs.txt", "Logs the channel in specified file. DEFAULT ARGUMENT(S): log_channel 'logs.txt'")
query.add_argument("content_filter", "str", "None", "Filter log by content. DEFAULT ARGUMENT(S): content_filter 'None'")
query.add_argument("log_attachments", "bool", True, "Logs attachments. DEFAULT ARGUMENT(S): log_attachments 'True'")
query.add_argument("log_author", "bool", False, "Logs author of message. DEFAULT ARGUMENT(S): log_author=False")
query.add_argument("exclude_content", "str", "None", "Exclude content from log. DEFAULT ARGUMENT(S): exclude_content='None'")

#FIRST EXAMPLE
message = "log_channel --h"
file_name = query.parse(message)
try: print(file_name['exclude_content'][0])
except: print(query.parse("--help"))

#SECOND EXAMPLE
message = "log_channel=example.txt, content_filter=posted, log_attachments=True, log_author=True, exclude_content='apple, pear, orange'"
file_name = query.parse(message)
try: print(file_name)
except: print(query.parse("--help"))

#THIRD EXAMPLE
message = "log_channel, exclude_content='apple, pear'"
file_name = query.parse(message)
try: print(file_name['exclude_content'])
except: print(query.parse("--help"))

#FOURTH EXAMPLE
message = "i made a booboo"
file_name = query.parse(message)
try: print(file_name['mistaken_content'][0])
except: print(query.parse("--help"))

希望这很有用:)