DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

python command-line interfaces

原文链接

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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第三方,提供更多的功能集,例如,读写文件?

1
2
3
4
5
6
7
8
9
10
11
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.',
)
1
2
3
4
5
6
7
8
> 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信息如何加入?

1
2
3
4
5
6
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)')

也是类似的

1
for key in tqdm(range(26)):

显示progress bar部分