cmdtemplate.py revision 375df4119909fb56f2bb8fd9f9a3193ae706c1c7
1#!/usr/bin/python
2
3#----------------------------------------------------------------------
4# Be sure to add the python path that points to the LLDB shared library.
5#
6# # To use this in the embedded python interpreter using "lldb" just
7# import it with the full path using the "command script import"
8# command
9#   (lldb) command script import /path/to/cmdtemplate.py
10#----------------------------------------------------------------------
11
12import lldb
13import commands
14import optparse
15import shlex
16
17def create_ls_options():
18    usage = "usage: %prog [options] <PATH> [PATH ...]"
19    description='''This command lets you run the /bin/ls shell command from
20within lldb. This code is designed to demonstrate the best principles that
21should be used when creating a new LLDB command through python.
22Creating the options in a separate function allows the parser to be
23created without running the command. The usage string is generated by the
24optparse module and can be used to populate the ls.__doc__ documentation
25string in the command interpreter function prior to registering the
26command with LLDB. The allows the output of "ls --help" to exactly match
27the output of "help ls" when both commands are run from within LLDB.
28'''
29    parser = optparse.OptionParser(description=description, prog='ls',usage=usage)
30    parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='display verbose debug info', default=False)
31    return parser
32
33def ls(debugger, command, result, dict):
34    # Use the Shell Lexer to properly parse up command options just like a
35    # shell would
36    command_args = shlex.split(command)
37    parser = create_ls_options()
38    try:
39        (options, args) = parser.parse_args(command_args)
40    except:
41        result.SetStatus (lldb.eReturnStatusFailed)
42        return
43
44    for arg in args:
45        if options.verbose:
46            result.PutCString(commands.getoutput('/bin/ls "%s"' % arg))
47        else:
48            result.PutCString(commands.getoutput('/bin/ls -lAF "%s"' % arg))
49
50def __lldb_init_module (debugger, dict):
51    # This initializer is being run from LLDB in the embedded command interpreter
52    # Make the options so we can generate the help text for the new LLDB
53    # command line command prior to registering it with LLDB below
54    parser = create_ls_options()
55    ls.__doc__ = parser.format_help()
56    # Add any commands contained in this module to LLDB
57    debugger.HandleCommand('command script add -f cmdtemplate.ls ls')
58    print 'The "ls" command has been installed, type "help ls" or "ls --help" for detailed help.'
59