我有一个使用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

最佳答案

哇,又一个反蟒蛇根之谜!你的问题和评论真的很有帮助为什么没有人用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>

09-10 03:51
查看更多