Neurohazard
暮雲煙月,皓首窮經;森羅萬象,如是我聞。

Create Beautiful Python Command-line Interface (POSIX C Fashion)

wpadmin~August 21, 2018 /Software Engineering

Contents

Create Beautiful Python Command-line Interface (POSIX C Fashion)

Summary

PyCon UK 2012: Create beautiful command-line interfaces with Python

github autobackup

Command-line Interface Standard
IEEE Std 1003.1 / POSIX

Some Option/Arugement Parser Library for Python

  1. optparse
  2. argparse
  3. docopt (Recommended)

Differences Between Argument, Option and Command

Argument (常规参数)

Angular Bracket ()

<argument> ARGUMENT

Option (可选参数)

Start with dash(-)
Option Argument (UPPERCASE)

-o, --option
-f FILE
--select=ERROR

Command (命令)

some example (一些案例)

my_program ship new <name>
my_program ship <name> move <x> <y> [--speed=<kn>]
my_program ship shoot <x> <y>
my_program mine (set|remove) <x> <y> [--mored|--drifing]
my_program -h | --help
my_program --version

其他

"|" pipe, vertical bar
"..." ellipsis

Demo

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)

在线测试工具

参考资料

1 PyCon UK 2012: Create beautiful command-line interfaces with Python

2 docopt——好用的Python命令行参数解释器
https://xuanwo.org/2016/04/04/docopt-intro/

3 代码示例
https://github.com/docopt/docopt/tree/master/examples

4 docopt:为Python程序创造一个优雅的命令行界面
http://hao.jobbole.com/docopt/

Leave a Reply

Your email address will not be published. Required fields are marked *