File: validation_example.py

package info (click to toggle)
python-docopt-ng 0.9.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 408 kB
  • sloc: python: 1,821; makefile: 3
file content (48 lines) | stat: -rw-r--r-- 1,065 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""Usage: prog.py [--count=N] PATH FILE...

Arguments:
  FILE     input file
  PATH     out directory

Options:
  --count=N   number of operations

"""
import os

from docopt import docopt

try:
    from schema import And
    from schema import Or
    from schema import Schema
    from schema import SchemaError
    from schema import Use
except ImportError:
    exit(
        "This example requires that `schema` data-validation library"
        " is installed: \n    pip install schema\n"
        "https://github.com/halst/schema"
    )


if __name__ == "__main__":
    args = docopt(__doc__)

    schema = Schema(
        {
            "FILE": [Use(open, error="FILE should be readable")],
            "PATH": And(os.path.exists, error="PATH should exist"),
            "--count": Or(
                None,
                And(Use(int), lambda n: 0 < n < 5),
                error="--count=N should be integer 0 < N < 5",
            ),
        }
    )
    try:
        args = schema.validate(args)
    except SchemaError as e:
        exit(e)

    print(args)