optparser: how to register callback to display binary's help

Jean-Michel Pichavant jeanmichel at sequans.com
Wed Oct 13 09:03:10 EDT 2010


hiral wrote:
> Hi,
>
> I want to display help message of python script and then display help
> message from the binary file (which also supports -h option):
>
> Assumptions:
> 1) 'mybinary' - is linux executable file which supports '-h' and on '-
> h' option it displays the help message
> 2) myscript.py - when passing '-h' option want to call 'mybinary -h'
> and display help messages of both script and binary.
>
> Code:
> ====
> from optparse import OptionParser
> [...]
> parser = OptionParser()
> parser.add_option("-e", "--execute", dest="file",
>                   help="Execute binary", metavar="FILE")
> (options, args) = parser.parse_args()
> if options.file:
>     subprocess.call(options.file)
>
>
> Requirement:
> $ python myscript.py -h
> <currently it prints the help message with '-e' and '-h' help message>
> <becides I want to display help message of 'mybinary'>
>
> Thank you in advance.
> -Hiral
>   

Hi,

Try something like

def myHelp(option, opt, value, parser):
    parser.print_help()
    if hasattr(parser.values, 'file') and parser.values.file:
        proc = subprocess.Popen([parser.values.file, '-h'], 
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print proc.stdout.read()
        print proc.stderr.read()

parser.remove_option('-h')
parser.add_option("-h", "--help",
                  help="display the help message", action='callback', 
callback = myHelp)


Jean-Michel




More information about the Python-list mailing list