Skip to content
gqlxj1987's Blog
Go back

python command-line interfaces

Edit page

原文链接

In order to achieve that, I advise you to respect 4 guidelines:

  1. You should provide default arguments values when possible
  2. All error cases should be handled (ex: a missing argument, a wrong type, a file not found)
  3. All arguments and options have to be documented
  4. A progress bar should be printed for not instantaneous tasks

We’re in luck: there is a Python library which offers the same features as argparse (and more), with a prettier code style: its name is click.

import click

from caesar_encryption import encrypt

@click.command()
@click.argument('text', nargs=-1)
@click.option('--decrypt/--encrypt', '-d/-e')
@click.option('--key', '-k', default=1)
def caesar(text, decrypt, key):
    text_string = ' '.join(text)
    if decrypt:
        key = -key
    cyphertext = encrypt(text_string, key)
    click.echo(cyphertext)

if __name__ == '__main__':
    caesar()

click第三方,提供更多的功能集,例如,读写文件?

import click

from caesar_encryption import encrypt

@click.command()
@click.option(
    '--input_file',
    type=click.File('r'),
    help='File in which there is the text you want to encrypt/decrypt.'
         'If not provided, a prompt will allow you to type the input text.',
)
> python caesar_script_v2.py --help
Usage: caesar_script_v2.py [OPTIONS]
Options:
  --input_file FILENAME          File in which there is the text you want to encrypt/decrypt. If not provided, a prompt will allow you to type the input text.
  --output_file FILENAME         File in which the encrypted/decrypted text will be written. If not provided, the output text will just be printed.
  -d, --decrypt / -e, --encrypt  Whether you want to encrypt the input text or decrypt it.
  -k, --key INTEGER              The numeric key to use for the caesar encryption / decryption.
  --help                         Show this message and exit.

还自带help的相关信息,argparse的help信息如何加入?

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

也是类似的

for key in tqdm(range(26)):

显示progress bar部分


Edit page
Share this post on:

Previous Post
Medium GraphQL server design
Next Post
Graph Algorithm