python argparse没有显示正确的帮助信息

时间:2016-06-10 13:43:45

标签: python override argparse

我有一个使用argparse的python脚本。在命令行上键入python script_name.py -h后,它会显示另一个命令的帮助消息,但代码仍然有效。该脚本可以识别其中定义的选项并运行良好。看起来脚本是由某种东西打包的。我把argparse放在一个函数中,一切都很好。我只是无法找出导致帮助消息发生变化的原因。

以下是代码:

#!/usr/bin/env python

import os
import sys
import json
import logging
import argparse
import handlers


HZZ_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(os.path.dirname(HZZ_DIR))
logger = logging.getLogger('hzz_logger')
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(console)


def parse_args():
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('job', choices=['ws','lm','np'],
            help="ws: workspace; lm: limit; np: npranking")
    arg_parser.add_argument('-a', '--action', nargs=1,
            help="for Limit and NPranking: get/plot (limit/pull)")
    arg_parser.add_argument('-b', '--blinded', action='store_true',
            help="for Limit: true -- do expected only, false -- do observed as well.")
    arg_parser.add_argument('-v', '--version', nargs=1, type=int,
            help="input version")
    arg_parser.add_argument('-t', '--tag', nargs=1,
            help='workspace tag')
    arg_parser.add_argument('-m', '--mass', nargs='+', type=int,
            help='signal mass(es)')
    arg_parser.add_argument('-c', '--config', nargs=1,
            help='configure file')
    arg_parser.add_argument('-u', '--update', action='store_true',
            help="update default settings")
    args = arg_parser.parse_args()
    return args

def load_settings(args):
    pass


def run_job(settings):
    pass


def execute():
    args = parse_args()
    settings = load_settings(args)
    run_job(settings)


if __name__ == '__main__':
    execute()

此处粘贴了帮助消息,这实际上是在此代码中未直接使用的命令的帮助消息。也可以识别此命令的选项......

$ python hzz_handler.py -h
Usage: python [-l] [-b] [-n] [-q] [dir] [[file:]data.root] [file1.C ... fileN.C]
Options:
  -b : run in batch mode without graphics
  -x : exit on exception
  -n : do not execute logon and logoff macros as specified in .rootrc
  -q : exit after processing command line macro files
  -l : do not show splash screen
 dir : if dir is a valid directory cd to it before executing

  -?      : print usage
  -h      : print usage
  --help  : print usage
  -config : print ./configure options
  -memstat : run with memory usage monitoring

2 个答案:

答案 0 :(得分:0)

哇,另一个反Python根源之谜!您的问题和评论确实很有帮助。为什么没有人用ROOT.PyConfig.IgnoreCommandLineOptions = True发布答案?

这是一个原始的解决方法:

import argparse

# notice! ROOT takes over argv and prints its own help message when called from command line!
# instead I want the help message for my script
# therefore, check first if you are running from the command line
# and setup the argparser before ROOT cuts in

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        formatter_class = argparse.RawDescriptionHelpFormatter,
        description = "my script",
        epilog = "Example:\n$ python my_script.py -h"
        )

    parser.add_argument("param", type=str, help="a parameter")
    parser.add_argument("-d", "--debug",    action='store_true', help="DEBUG level of logging")

    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    logging.debug("parsed args: %s" % repr(args))


import ROOT

...

if __name__ == '__main__':
    <do something with args>

答案 1 :(得分:0)

在排序中,答案是始终在 argparse 之后调用 import ROOT。然后 ROOT 不会接管 argparse 并打印我们想要的所需消息。