Welcome, guest | Sign In | My Account | Store | Cart

This little sample script looks up in locals() to determine all the callables in main.

Then it passes them to parse_arguments, which show an help message as following usage:

prova.py [-h] {func2,func1}

positional arguments:
  {func2,func1}

optional arguments:
  -h, --help     show this help message and exit

Useful to avoid duplication and make it easy to extend script functions.

Python, 34 lines
 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
import argparse

# this function can be anywhere
def get_list_of_local_callables():
    """Generate and return the list of the local callables
    """
    from inspect import stack
    caller_locals = stack()[1][0].f_locals
    loc_callables = dict((k, v) for k, v in caller_locals.items()
                         if callable(v))

    return loc_callables


# and we can use it simply with
def parse_arguments(actions):
    parser = argparse.ArgumentParser()
    parser.add_argument("action", choices=actions)
    return parser.parse_args()

def main():
    def func1():
        pass

    def func2():
        pass

    loc_funs = get_list_of_local_callables()
    ns = parse_arguments(loc_funs.keys())

    loc_funs[ns.action]()

if __name__ == '__main__':
    main()
Created by Andrea Crotti on Mon, 14 Nov 2011 (MIT)
Python recipes (4591)
Andrea Crotti's recipes (1)

Required Modules

Other Information and Tasks