How do I return a value when @click.option is used to pass a command line argument to a function?

后端 未结 4 2144
慢半拍i
慢半拍i 2021-02-20 04:31

I am trying to use click python package to pass a command line argument to a function. The example from official documentation works as explained. But nowhere in the documentati

4条回答
  •  心在旅途
    2021-02-20 04:45

    Apparently this click package makes your hello() function never return. So the print never happens. If I were you, I would not use this unintuitive package and instead use argparse which is great at command line processing in Python (one of the best in any language, in my opinion).

    Here's a working version of your code using argparse. It works out-of-the-box with Python (any version 2.7 or later), and it's easy to understand.

    def hello(count):
        """Simple program that greets NAME for a total of COUNT times."""
        for x in range(count):
            print('Hello')
        return "hello hi"
    
    if __name__ == '__main__':
        import argparse
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument('--count', default=3, type=int, help='Number of greetings.')
        args = parser.parse_args()
    
        print(hello(args.count))
    

提交回复
热议问题