[Docpie]

Fork me on GitHub

Advanced APIs


docpie arguments

from docpie import docpie
docpie(doc, argv=None, help=True, version=None,
       stdopt=True, attachopt=True, attachvalue=True,
       auto2dashes=True, name=None, case_sensitive=False,
       optionsfirst=False, appearedonly=False, extra={})

Note

For these arguments, pass key-word value instead of positional value.

auto2dashes

type: bool; default: True

When set to True, docpie will handle -- (which means "end of command line flag", see here) automatically.

from docpie import docpie
print(docpie('Usage: prog <file>'), ['prog', '--', '--test'])
# {'--': True, '<file>': '--test'}

try it >>

name

type: str; default: None

name is the "name" of your program. In each of your "usage" the "name" will be ignored. When set to None, docpie will ignore the first element of your "usage"

"""
Usage:
    myscript.py config
    $ python myscript.py make
    $ sudo python myscript.py make install
"""
from docpie import docpie
print(docpie(__doc__, ['myscript.py', 'make', 'install'], name='myscript.py'))
# {'--': False,
#  'config': False,
#  'install': True,
#  'make': True}

try it >>

case_sensitive

type: bool; default: False

case_sensitive specifies if it need to be case sensitive when matching "Usage:" and "Options:"

optionsfirst

type: bool; default: False

If set to True, any elements after the first positional elements in argv will be interpreted as positional argument.

"""
Usage: sudo [-v] [<command>] [<options>...]
"""

from docpie import docpie
import sys

sys.argv = ['sudo', 'cp', '-v', 'a.txt', '/tmp']
print(docpie(__doc__, optionsfirst=True))
# {'--': False,
#  '-v': False,
#  '<command>': 'cp',
#  '<options>': ['-v', 'a.txt', '/tmp']}

sys.argv = ['sudo', '-v', 'cp', '-v', 'a.txt', '/tmp']
print(docpie(__doc__, optionsfirst=True))
# {'--': False,
#  '-v': True,
#  '<command>': 'cp',
#  '<options>': ['-v', 'a.txt', '/tmp']}

try it >>

It's useful when you need to dispatch your program with others. See example-get

appearedonly

type: bool; default: False

Note

  1. You may not need this argument when you follow the POSIX standard
  2. This argument only affect option

When set to True, docpie will not add options that never appeared in argv. Consider the following situation:

Usage: prog [options]

Options:
   -s, --sth=[<value>]    Just an example. Not POSIX standard

For argv is ['prog'] or ['prog', '--sth'], the results will both be --sth=None. But if you set appearedonly=False, then for the first case, --sth will not appear in the result.

from docpie import docpie
args = docpie(__doc__)
if '--sth' in args:
    if args['--sth'] is None:
        print('--sth is in argv without value')
    else:
        print('--sth is in argv with value %s' % args['--sth'])
else:
    print('--sth is not in argv')

extra

See the Docpie section below


Docpie Object

Summary

Normally the docpie and the basic arguments are all your need, But you can do more tricks with Docpie class.

When call

from docpie import docpie
print(docpie(__doc__))

It's equal to:

from docpie import Docpie
pie = Docpie(__doc__)
pie.docpie()
print(pie)

Docpie accepts any arguments of docpie except argv

Docpie(doc, help=True, version=None,
       stdopt=True, attachopt=True, attachvalue=True,
       auto2dashes=True, name=None, case_sensitive=False,
       optionsfirst=False, appearedonly=False, extra={})

Docpie.docpie accepts argv argument. As it's said before, use sys.argv when it's set to None

Docpie.docpie(argv=None)

Auto Handle

When help=True or version="sth", docpie will automatically handle these arguments.

Taking version="0.0.1" as an example, docpie will deal with it following these steps:

  1. check if "--version" is defined in "Options"
  2. if so, map all the synonymous options to function Docpie.version_handler
  3. otherwise, check if -v is defined in "Options", and do similar work as step 2
  4. if neither -v nor --version is defined in "Options", then just map --version & -v to Docpie.version_handler
  5. Check whether these option-s in argv.
  6. If find the option, to say --version, then call Docpie.version_handler(pie, "--version"). the pie is the instance of Docpie
  7. By default, print the value of version and exit

You can use extra argument or set_auto_handler function to change the default behavior.

extra argument

extra is a dict, the key is the name of the auto-handled option, the value is a callback object which accepts two arguments: the first one is the Docpie instance, the second one is the name of this option.

When argv contain this option, Docpie will call the callback object first.

"""
Example for Docpie!

Usage: example.py [options]

Options:
  -v, --obvious    print more infomation  # note the `-v` is here
  --version        print version
  -h, -?, --help   print this infomation

Hidden Options:
  --moo            the Easter Eggs!

Have fun, my friend.
"""
from docpie import Docpie
import sys


def moo_handler(pie, flag):
    print("Alright you got me. I'm an Easter Egg.\n"
          "You may use this program like this:\n")
    print(pie.usage_text)
    print("")    # compatible python2 & python3
    print(pie.option_sections[''])
    sys.exit()    # Don't forget to exit

pie = Docpie(__doc__, version='0.0.1')
pie.set_config(
  extra={
    '--moo': moo_handler,  # set moo handler
  }
)

pie.docpie()
print(pie)

Now when pass --moo, it will run moo_handler (note: see next part for pie.option_sections).

Now try:

example.py -v
example.py --version
example.py --moo

set_auto_handler function

Docpie.set_auto_handler(flag, handler)

When set extra, the synonymous options you defined will not be checked by Docpie. But set_auto_handler can do the check and make all synonymous options have the same behavior.

flag is the name of auto-handled option, handler is a callable object wich accept Docpie instance and the name of the option as it's arguments.

"""
Usage: [options]

Options: --moo, -m     the Easter Eggs!
"""

from docpie import Docpie
import sys

def moo_handler(pie, flag):
    print("I'm an Easter Egg!")
    sys.exit()

pie = Docpie(__doc__)
pie.set_auto_handler('-m', moo_handler)
pie.docpie()
print(pie)

Now Docpie will handle both -m and --moo.

Docpie Attribute

The callable object in extra & set_auto_handler will get a Docpie instance. The following attribute may help you customize the behavior.

pie = Docpie(__doc__)
  • pie.version is the version you set (default: None)
  • pie.usage_text is the "Usage" section you write
  • pie.option_sections is a dict, which contains all the "Options" sections you write. The key is the characters before "Options:" (white spaces not include):
    usage: example.py <command> [options]
    
    # the key will be an empty string
    options:
       -h, --help        print this message
    
    # the key will be 'help'
    help options:
       -o, --out=<file>  output file
    
    # the key will be 'advanced control'
    advanced control options:
       -u, --up          move upward
       -d, --down        move downward
    

set_config

set_config(help=True, version=None,
           stdopt=True, attachopt=True, attachvalue=True,
           auto2dashes=True, name=None, case_sensitive=False,
           optionsfirst=False, appearedonly=False, extra={})

set_config can shadow any argument you passed to Docpie except doc.

Note

change stdopt, attachopt, attachvalue, case_sensitive, name will cause the Docpie re-initialize. Create a new Docpie instead.


If you like this project, you can buy me a beer to help me make it better! | Flattr this

侧栏导航