Use of click tool

1: Click navigation

  • Address: https://click.palletsprojects.com/en/8.0.x/
  • Install click: pip install Click
  • See literature: https://isudox.com/2016/09/03/learning-python-package-click/

2: Basic use of Click

1: Official website case demonstration:

  • Official website case code:

    # hello.py
    import click
    
    @click.command()
    @click.option('--count', default=1, help='Number of greetings.')
    @click.option('--name', prompt='Your name',
                  help='The person to greet.')
    def hello(count, name):
        """Simple program that greets NAME for a total of COUNT times."""
        for x in range(count):
            click.echo('Hello %s!' % name)
    
    if __name__ == '__main__':
        hello()
    
  • Copy the code to hello Py file, execute: Python hello py --count=3

    (flask_env) C:\Users\renshanwen\Desktop>python hello.py --count=3
    Your name: liangshan
    Hello liangshan!
    Hello liangshan!
    Hello liangshan!
    
  • Execute Python hello py --help

    (flask_env) C:\Users\renshanwen\Desktop>python hello.py --help
    Usage: hello.py [OPTIONS]
    
      Simple program that greets NAME for a total of COUNT times.
    
    Options:
      --count INTEGER  Number of greetings.
      --name TEXT      The person to greet.
      --help           Show this message and exit.
    

2: @click.command decorator

  • @click. The command () decorator decorates a function method as a command line interface.

    import click
    @click.command()
    def hello():
        click.echo('Hello World!')
    
    • @click. The Command () decorator turns the hello() method into a Command object, and when it is called, it executes the behavior within the instance. The -- help parameter is the built-in parameter of the Command object.

3: @click. Group decorator:

  • Different Command instances can be associated to a group. The Command bound under group becomes its subcommand.

  • @click. The Group decorator decorates methods as Group objects that can have multiple subcommands. By Group add_ The Command () method associates a Command object with a Group object.

    @click.group()
    def cli():
        pass
    
    @click.command()
    def initdb():
        click.echo('Initialized the database')
    
    @click.command()
    def dropdb():
        click.echo('Dropped the database')
    
    cli.add_command(initdb)
    cli.add_command(dropdb)
    
  • You can also directly use @ Group Command decoration method will automatically associate the method to the Group object.

    @click.group()
    def cli():
        pass
    
    @cli.command()
    def initdb():
        click.echo('Initialized the database')
    
    @cli.command()
    def dropdb():
        click.echo('Dropped the database')
    

4: Command line parameters

  • Click supports adding custom parameters to the command method, which is implemented by the option() and argument() decorators.

  • Case:

    @click.command()
    @click.option('--count', default=1, help='number of greetings')
    @click.argument('name')
    def hello(count, name):
        for x in range(count):
            click.echo('Hello %s!' % name)
    

4.1: Option parameter:

  • '– parameter name', indicating the entered parameter.

  • default = default

  • nargs = number, indicating the number of parameters.

  • Type = type, which limits the type of parameter.

  • multiple=True, allowing a parameter to be used multiple times.

  • prompt=True, friendly prompt for command input error.

  • Case:

    @click.command()
    @click.option('--pos', nargs=2, type=float)
    def findme(pos):
        click.echo('%s / %s' % pos)
        
    #findme --pos 2.0 3.0 
    # The output is 2.0 / 3.0
    
  • If -- pos=2 is followed on the command line, it will be output twice. By default, it is executed once.

  • type can also specify different types:

    @click.command()
    @click.option('--item', type=(unicode, int))
    def putitem(item):
        click.echo('name=%s id=%d' % item)
    #putitem --item peter 1338, the output is name=peter id=1338
    
  • A parameter is passed in multiple times:

    • option supports this feature through the multiple identification bit.
    import click
    
    @click.command()
    @click.option('--message', '-m', multiple=True)
    def commit(message):
        click.echo('\n'.join(message))
    
    if __name__ == '__main__':
        commit()
    
    (flask_env) C:\Users\renshanwen\Desktop>python commit.py -m liangshan -m dada
    liangshan
    dada
    
  • Limit the type range of parameters passed:

    • When the above command line program parameter -- hash type is not md5 or sha1, an error prompt will be output, and the choice option will also be displayed in the -- help prompt.
    import click
    
    @click.command()
    @click.option('--hash_type', type=click.Choice(['md5', 'sha1']))
    def digest(hash_type):
        click.echo(hash_type)
    
    if __name__ == '__main__':
        digest()
    
    # Correct demonstration
    (flask_env) C:\Users\renshanwen\Desktop>python commit.py --hash_type md5
    md5
    # Error presentation
    (flask_env) C:\Users\renshanwen\Desktop>python commit.py --hash_type xxx
    Usage: commit.py [OPTIONS]
    Try 'commit.py --help' for help.
    
    Error: Invalid value for '--hash_type': 'xxx' is not one of 'md5', 'sha1'.
    
  • Friendly prompt presentation:

    # prompt
    @click.command()
    @click.option('--name', prompt=True)
    def hello(name):
        click.echo('Hello %s!' % name)
    
    (flask_env) C:\Users\renshanwen\Desktop>python commit.py --name liangshan
    Hello liangshan!
    
    (flask_env) C:\Users\renshanwen\Desktop>python commit.py
    Name:
    Name:
    Name: liangshan
    Hello liangshan!
    
    • Custom prompt parameters:
    import click
    
    @click.command()
    @click.option('--name', prompt="Please enter a name")
    def hello(name):
        click.echo('Hello %s!' % name)
    
    if __name__ == '__main__':
        hello()
        
    (flask_env) C:\Users\renshanwen\Desktop>python commit.py
     Please enter a name:
    Please enter a name: liangshan
    Hello liangshan!
    
  • Enter and hide the password:

    import click
    
    @click.command()
    @click.option('--password', prompt=True, hide_input=True,
                  confirmation_prompt=True)
    def encrypt(password):
        click.echo('Encrypting password to %s' % password)
    
    if __name__ == '__main__':
        encrypt()
    
    (flask_env) C:\Users\renshanwen\Desktop>python commit.py
    Password:
    Repeat for confirmation:
    Encrypting password to 123456
    
    # Change to decorator writing:
    @click.command()
    @click.password_option()
    def encrypt(password):
        click.echo('Encrypting password to %s' % password.encode('rot13'))
    

4.2: Argument parameter:

  • 1: Use argument to pass parameters:

    import click
    
    @click.command()
    @click.argument('filename')
    def touch(filename):
        click.echo(filename)
    
    if __name__ == '__main__':
        touch()
    
    (flask_env) C:\Users\renshanwen\Desktop>python commit.py liangshan
    liangshan
    
  • 2: Use argument to pass parameters (variable parameters)

    • nargs=-1

    • Analysis: we found that src is a variable parameter and dst is a limited parameter.

      import click
      
      @click.command()
      @click.argument('src', nargs=-1)
      @click.argument('dst', nargs=1)
      def copy(src, dst):
          for fn in src:
              click.echo('move %s to folder %s' % (fn, dst))
      
              
      if __name__ == '__main__':
          copy()
      
      
      (flask_env) C:\Users\renshanwen\Desktop>python commit.py aaa bbb ccc AAA
      move aaa to folder AAA
      move bbb to folder AAA
      move ccc to folder AAA
      
  • 3: To operate on a file:

    • Note: use - as standard input and output.
    • If you just want to modify the file name: type = click Path(exists=True)
    @click.command()
    @click.argument('input', type=click.File('rb'))
    @click.argument('output', type=click.File('wb'))
    def inout(input, output):
        while True:
            chunk = input.read(1024)
            if not chunk:
                break
            output.write(chunk)
    
    $ inout - hello.txt
    hello
    ^D
    
    $ inout hello.txt -
    hello
    
    @click.command()
    @click.argument('f', type=click.Path(exists=True))
    def touch(f):
        click.echo(click.format_filename(f))
    

5: Packaged as a cross platform executable

  • Scheme 1: the simplest way is to add the following code at the end of the file:

    if __name__ == '__main__':
        command()
    
  • Scheme 2: Click supports the use of setuptools to better package command-line programs, package source files into executable programs in the system, and is not limited to platforms.

    • Generally, we will create setup. Exe in the root directory of the source code Py script.

    • entry_points field, in console_ Under scripts, each line is a console script. On the left of the equal sign is the name of the script, and on the right is the import path of the Click command.

      from setuptools import setup
      
      setup(
          name='hello',
          version='0.1',
          py_modules=['hello'],
          install_requires=[
              'Click',
          ],
          entry_points='''
              [console_scripts]
              hello=hello:cli
          ''',
      )
      

Keywords: Python

Added by vigiw on Sun, 16 Jan 2022 15:43:02 +0200