python argparse 不显示正确的帮助消息

Yic*_*eng 6 python overriding argparse pyroot

我有一个使用 python 脚本argparse。在命令行中输入后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()
Run Code Online (Sandbox Code Playgroud)

这里粘贴的是帮助信息,实际上是这段代码中没有直接使用的命令的帮助信息。该命令的选项也可以被识别...

$ 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
Run Code Online (Sandbox Code Playgroud)

xea*_*its 1

哇,又一个反 Python 的 ROOT 之谜!您的问题和评论非常有帮助。为什么没有人用 发布答案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>
Run Code Online (Sandbox Code Playgroud)