def test_tethys_app_uninstall_add_arguments(self): parser = ArgumentParser('foo_parser') cmd = tethys_app_uninstall.Command() cmd.add_arguments(parser) self.assertIn('foo_parser', parser.format_usage()) self.assertIn('app_or_extension', parser.format_usage()) self.assertIn('[-e]', parser.format_usage()) self.assertIn('--extension', parser.format_help())
def test_syncstores_add_arguments(self): parser = ArgumentParser() cmd = syncstores.Command() cmd.add_arguments(parser) self.assertIn('app_name', parser.format_usage()) self.assertIn('[-r]', parser.format_usage()) self.assertIn('[-f]', parser.format_usage()) self.assertIn('[-d DATABASE]', parser.format_usage()) self.assertIn('--refresh', parser.format_help()) self.assertIn('--firsttime', parser.format_help()) self.assertIn('--database DATABASE', parser.format_help())
class BaseCommand(ABC): def __init__(self, name, desc): self.name = name self.parser = ArgumentParser(description=desc) prog = self.parser.prog self.parser.prog = f"{prog} {self.name}" def __call__(self, args): parsed_args = self.parser.parse_args(args) return self.run(parsed_args) def format_help(self): wrapper = TextWrapper() lines = wrapper.wrap(f" {self.name:8}{self.parser.description}") first, rest = lines[0], lines[1:] final = [first] for line in rest: final.append(" " * 10 + line) return "\n".join(final) def format_usage(self): usage = self.parser.format_usage() usage = usage.replace(self.parser.prog, f"{self.parser.prog} {self.name}") return f"" @abstractmethod def run(self, args) -> int: pass
def compose(parser=None, **kwargs): if not parser: parser = ArgumentParser(**kwargs) parser.usage = "python -m " + parser.format_usage().split(':')[1].strip() return parser
def _create_invalid_arguments_msg(argparser: argparse.ArgumentParser, argument_dict: Dict[str, str], details: Optional[str]) -> str: msg = [] if len(argument_dict) == 0: pass elif len(argument_dict) == 1: for arg_name, arg_val in argument_dict.items(): msg.append(f'Invalid argument: {arg_name} = {arg_val}') else: msg.append('Invalid arguments:') for arg_name, arg_val in argument_dict.items(): msg.append(f' {arg_name} = {arg_val}') if len(argument_dict) > 0: msg.append('') if details is not None: msg.append(details) msg.append('') msg.append(argparser.format_usage()) return '\n'.join(msg)
def compose(parser=None, **kwargs): if not parser: parser = ArgumentParser(**kwargs) root_help_dict = {"curdir": os.curdir, "cwd": os.getcwd()} parser.add_argument( "root", type=_directory, help=( "The directory to begin test discovery. Use '{curdir}' " + "for the current working directory: {cwd}" ).format(**root_help_dict), ) parser.add_argument( "-p", "--pattern", default=".*", type=_regex, help="Only modules whose name fits this pattern will be " + "searched. (default: %(default)s)", ) main.compose(parser) parser.usage = "python -m " + parser.format_usage().split(":")[1].strip() return parser
def test_collectworkspaces_add_arguments(self): from argparse import ArgumentParser parser = ArgumentParser() cmd = collectworkspaces.Command() cmd.add_arguments(parser) self.assertIn('[-f]', parser.format_usage()) self.assertIn('--force', parser.format_help()) self.assertIn('Force the overwrite the app directory', parser.format_help())
def install_command_parser(**kwargs): global _parser _parser = ArgumentParser(**kwargs) command_parsers_help = "Specify a command to the PyInq package." command_parsers = _parser.add_subparsers(help=command_parsers_help) _install_discovery_parser(command_parsers) _parser.usage = "python -m " + _parser.format_usage().split(':')[1].strip()
class ArgumentCommand(Command): """A base command with argparse support rolled in.""" def __init__(self, manager): """Initialize the command with an argument parser.""" super(ArgumentCommand, self).__init__(manager) prog = "{} {}".format(os.path.basename(sys.argv[0]), self.name) self.argparser = ArgumentParser(add_help=False, prog=prog) self.options = None self.args = None self.add_arguments() def add_arguments(self): """Build the argument parser here. It's in self.argparser.""" def parse_args(self, args, known=False): """ Parse arguments into self.options. Flatten out any action=store values with nargs=1 or None. If known is True then only parse known args and place the remaining args into self.args. """ def get_valid_action(dest): for action in self.argparser._actions: if isinstance(action, _StoreAction) and action.dest == dest: if action.nargs is None or action.nargs == 1: return action break return None if known: self.options, self.args = self.argparser.parse_known_args(args[1:]) else: self.options = self.argparser.parse_args(args[1:]) for name, value in self.options.__dict__.iteritems(): if hasattr(value, '__iter__'): action = get_valid_action(name) if action: setattr(self.options, name, value[0]) def get_usage(self): """Print usage text generated from argparse.""" usage = self.argparser.format_usage().strip() return re.sub(r'^usage:\s[^\s]+\s[^\s]+\s', '', usage) def get_help(self): """Print help text generated from argparse.""" text = self.argparser.format_help() regex = re.compile(r'^optional arguments') while text and not regex.match(text): start = text.find('\n') + 1 text = text[start:] return text def run(self, args): """Parse the commandline arguments.""" self.parse_args(args)
def install_command_parser(**kwargs): global _parser _parser = ArgumentParser(**kwargs) command_parsers_help = "Specify a command to the PyInq package." command_parsers = _parser.add_subparsers(help=command_parsers_help) _install_discovery_parser(command_parsers) _install_test_parser(command_parsers) _parser.usage = "python -m " + _parser.format_usage().split(':')[1].strip()
def configure(self, parser: ArgumentParser): super().configure(parser) parser.add_argument('-i', '--interactive', action='store_true', help='Pass STDIN to the container') parser.add_argument('-t', '--tty', action='store_true', help='Allocate a pseudo-TTY') parser.add_argument('-u', '--user', type=str, default=None, help='Container username or UID (format: <name|uid>[:<group|gid>])') parser.add_argument('--no-sync', action='store_true', help='Don\'t sync the project before running the script') # add the "double-dash" argument to the usage message parser.prog = 'spotty exec' parser.usage = parser.format_usage()[7:-1] + ' -- COMMAND [args...]\n' parser.epilog = 'The double dash (--) separates the command that you want to execute inside the container ' \ 'from the Spotty arguments.'
def format_usage(parser: ArgumentParser, depth: int, invalid_args=None) -> None: usage = parser.format_usage() args = list( filter(lambda arg: arg != "-h" and arg != "--help", sys.argv[:depth])) args[0] = parser.prog if invalid_args: invalid_args = " ".join(invalid_args) if invalid_args in args: args.remove(invalid_args) nusg = " ".join(args) parser.usage = usage.replace(f"Usage: {parser.prog}", nusg, 1)
def get_args(): parser = ArgumentParser(description=__doc__, formatter_class=fmt) add = parser.add_argument # shortcut add('files', metavar='FILE', nargs='*', help='file to sync') add('--location', default='bb:sync', help='central sync storage') add('--list', action='store_true', help='list tracked files') add('--init', action='store_true', help='create initial file sync') add('--delete-backups', action='store_true', help='delete (most) backups') args = parser.parse_args() if not args.files and not args.list: sys.exit(parser.format_usage().strip()) return args
def compose(parser=None, **kwargs): if not parser: parser = ArgumentParser(**kwargs) root_help_dict = {"curdir": os.curdir, "cwd": os.getcwd()} parser.add_argument("root",type=_directory, help=("The directory to begin test discovery. Use '{curdir}' " + \ "for the current working directory: {cwd}").format(**root_help_dict)) parser.add_argument("-p","--pattern",default=".*",type=_regex, help="Only modules whose name fits this pattern will be " + \ "searched. (default: %(default)s)") main.compose(parser) parser.usage = "python -m " + parser.format_usage().split(':')[1].strip() return parser
def configure(self, parser: ArgumentParser): super().configure(parser) parser.add_argument('script_name', metavar='SCRIPT_NAME', type=str, help='Script name') parser.add_argument( '-u', '--user', type=str, default=None, help='Container username or UID (format: <name|uid>[:<group|gid>])' ) parser.add_argument('-s', '--session-name', type=str, default=None, help='tmux session name') parser.add_argument('-l', '--logging', action='store_true', help='Log the script outputs to a file') parser.add_argument( '-p', '--parameter', metavar='PARAMETER=VALUE', action='append', type=str, default=[], help= 'Set a value for the script parameter (format: PARAMETER=VALUE). This ' 'argument can be used multiple times to set several parameters. Parameters can be ' 'used in the script as Mustache variables (for example: {{PARAMETER}}).' ) parser.add_argument( '--no-sync', action='store_true', help='Don\'t sync the project before running the script') # add the "double-dash" argument to the usage message parser.prog = 'spotty run' parser.usage = parser.format_usage()[7:-1] + ' [-- args...]\n' parser.epilog = 'The double dash (--) separates custom arguments that you can pass to the script ' \ 'from the Spotty arguments.'
def main(): parser = ArgumentParser(description=DESCRIPTION) parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity") parser.add_argument( '-c', '--configuration', default=DEFAULT_CONFIG_FILE, required=False, help= "The path of the configuration file: it must be a json file with two keys: \"api_key\" " "and \"endpoint\"") parser.add_argument('-k', '--api_key', default=None, required=False, help="The API key (overrides the configuration)") parser.add_argument('-e', '--endpoint', default=None, required=False, help="The endpoint (overrides the configuration)") subparsers = parser.add_subparsers() for module in COMMANDS: module.add_command(subparsers) args = parser.parse_args() configure_logger(args) client = create_client(args) try: callable_ = args.function except AttributeError: print(parser.format_usage()) else: loop = asyncio.get_event_loop() loop.run_until_complete(callable_(args, client))
class CmdArgs(object): """Manage command line arguments.""" _p = None def __init__(self): self._p = ArgumentParser(prog='pydor', description='PYthon Dependencies vendOR') self._p.add_argument('--version', action='version', version='%(prog)s version ' + __version__) self._p.add_argument('--debug', action='store_true', default=False, help='enable all debug settings') self._p.add_argument('--log', help='set log level (default: warning)', default='warning', metavar='level') self.addSubparsers() def addSubparsers(self): """Add a subparser with options for sub commands.""" p = self._p.add_subparsers( title='commands', description='run `pydor command -h` for more information', help='description') proxy.cmdArgs(p) def parseArgs(self, argv): """Parse command args, then set log level from parsed options.""" return self._p.parse_args(args=argv) def printUsage(self): msg = self._p.format_usage() log.error(msg)
def _parse_args(cli_args): """Return the results of parsing the specified command-line arguments. Arguments: cli_args (list<str>): The arguments, excluding the program. Returns: Namespace: The results. """ parser = ArgumentParser( description='Utilities for the eink-server Python library.', prog='einkserver') subparsers = parser.add_subparsers(dest='command') subparsers.add_parser( 'skeleton', description='Generate skeleton code for an e-ink server.') connect_parser = subparsers.add_parser( 'connect', description='Connect to an e-ink server, and display what would ' 'be shown on the e-ink display.') connect_parser.add_argument('url', help='the server URL to connect to', metavar='URL') parsed_args = parser.parse_args(cli_args) if parsed_args.command is None: # Ideally, we would use required=True instead. But that isn't # available until Python 3.7, and it's not worth increasing the # required version of Python. print(parser.format_usage(), end='', file=sys.stderr) print( 'einkserver: error: the following arguments are required: ' 'command', file=sys.stderr) sys.exit(1) return parsed_args
def _mk_usage(self, parser: ArgumentParser) -> literal_block: parser.formatter_class = lambda prog: HelpFormatter(prog, width=self.options.get("usage_width", 100)) texts = parser.format_usage()[len("usage: ") :].splitlines() texts = [line if at == 0 else f"{' ' * (len(parser.prog) + 1)}{line.lstrip()}" for at, line in enumerate(texts)] return literal_block("", Text("\n".join(texts)))
def main(): parser = ArgumentParser(description='Convert kaldi data directory to uem dat files', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--verbose', type=int, \ dest='verbose', default=0, \ help='Give higher verbose for more logging') parser.add_argument('--get-text', action='store_true', \ help='Get text in dat file') parser.add_argument('--prefix', type=str, \ help='Add db file name as db-<prefix>-{utt/spk}.dat') parser.add_argument('kaldi_dir', \ help='Kaldi data directory') parser.add_argument('output_dir', \ help='Directory to store uem dat files') parser.usage=':'.join(parser.format_usage().split(':')[1:]) \ + 'e.g. : %(prog)s --prefix 203-lao-v0 data/dev10h.seg CMU_db' options = parser.parse_args() if options.get_text: try: text_file = open(options.kaldi_dir+'/text', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/text')) sys.exit(1) try: segments_file = open(options.kaldi_dir+'/segments', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/segments')) sys.exit(1) try: scp_file = open(options.kaldi_dir+'/wav.scp', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/wav.scp')) sys.exit(1) reco2file_map = {} for line in scp_file.readlines(): splits = line.strip().split() m = re.search(r".*/(?P<file_name>[0-9A-Za-z_]*\.(sph|wav)).*", line) if not m: sys.stderr.write("%s does not contain a valid speech file (.wav or .sph)\n" % line.strip()) sys.exit(1) reco2file_map[splits[0]] = m.group('file_name') # End for spk2utt_map = {} if options.prefix == None: prefix = options.kaldi_dir.split('/')[-1].split('.')[0] else: prefix = options.prefix try: utt_dat = open(options.output_dir+'/db-'+prefix+'-utt.dat', 'w') spk_dat = open(options.output_dir+'/db-'+prefix+'-spk.dat', 'w') except IOError as e: repr(e) sys.stderr.write("%s: Could not write dat files in %s\n" % (sys.argv[0], options.output_dir)) sys.exit(1) for line in segments_file.readlines(): utt_id, file_id, start, end = line.strip().split() if (options.get_text): splits = text_file.readline().split() while splits[0] < utt_id: splits = text_file.readline().split() text = ' '.join(splits[1:]) else: text = "" utt_dat.write("{UTTID %s} {UTT %s} {SPK %s} {FROM %s} {TO %s} {TEXT %s}\n" % (utt_id, utt_id, file_id, start, end, text)) spk2utt_map.setdefault(file_id, []) spk2utt_map[file_id].append(utt_id) for spk, utts in spk2utt_map.items(): try: spk_dat.write("{SEGS %s} {ADC %s} {CONV %s.wav} {CHANNEL 1} {DUR }\n" % (' '.join(utts), reco2file_map[spk], spk)) except KeyError as e: repr(e) sys.stderr.write("%s: Error in getting file for %s\n" % (sys.argv[0], spk)) sys.exit(1) # End for segments_file.close() utt_dat.close() spk_dat.close()
def unittest(args): """run the JUnit tests""" junit_arg_actions = [] junit_args = [] class MxJUnitWrapperArg(Action): def __init__(self, **kwargs): kwargs['required'] = False Action.__init__(self, **kwargs) junit_arg_actions.append(self) def __call__(self, parser, namespace, values, option_string=None): junit_args.append('-' + self.dest) junit_args.append(values) class MxJUnitWrapperBoolArg(Action): def __init__(self, **kwargs): kwargs['required'] = False kwargs['nargs'] = 0 Action.__init__(self, **kwargs) junit_arg_actions.append(self) def __call__(self, parser, namespace, values, option_string=None): junit_args.append('-' + self.dest) parser = ArgumentParser( prog='mx unittest', description='run the JUnit tests', formatter_class=RawDescriptionHelpFormatter, epilog=unittestHelpSuffix, ) parser.add_argument('--blacklist', help='run all testcases not specified in <file>', metavar='<file>') parser.add_argument('--whitelist', help='run testcases specified in <file> only', metavar='<file>') parser.add_argument('--verbose', help='enable verbose JUnit output', dest='JUnitVerbose', action=MxJUnitWrapperBoolArg) parser.add_argument('--very-verbose', help='enable very verbose JUnit output', dest='JUnitVeryVerbose', action=MxJUnitWrapperBoolArg) parser.add_argument( '--max-class-failures', help= 'stop after N test classes that have a failure (default is no limit)', metavar='<N>', dest='JUnitMaxClassFailures', action=MxJUnitWrapperArg) parser.add_argument('--fail-fast', help='alias for --max-class-failures=1', dest='JUnitFailFast', action=MxJUnitWrapperBoolArg) parser.add_argument( '--enable-timing', help='enable JUnit test timing (requires --verbose/--very-verbose)', dest='JUnitEnableTiming', action=MxJUnitWrapperBoolArg) parser.add_argument( '--regex', help='run only testcases matching a regular expression', metavar='<regex>') parser.add_argument('--color', help='enable color output', dest='JUnitColor', action=MxJUnitWrapperBoolArg) parser.add_argument('--gc-after-test', help='force a GC after each test', dest='JUnitGCAfterTest', action=MxJUnitWrapperBoolArg) parser.add_argument( '--record-results', help='record test class results to passed.txt and failed.txt', dest='JUnitRecordResults', action=MxJUnitWrapperBoolArg) parser.add_argument('--suite', help='run only the unit tests in <suite>', metavar='<suite>') parser.add_argument('--repeat', help='run each test <n> times', dest='JUnitRepeat', action=MxJUnitWrapperArg, type=is_strictly_positive, metavar='<n>') parser.add_argument( '--open-packages', dest='JUnitOpenPackages', action=MxJUnitWrapperArg, metavar='<module>/<package>[=<target-module>(,<target-module>)*]', help= "export and open packages regardless of module declarations (see more detail and examples below)" ) eagerStacktrace = parser.add_mutually_exclusive_group() eagerStacktrace.add_argument( '--eager-stacktrace', action='store_const', const=True, dest='eager_stacktrace', help='print test errors as they occur (default)') eagerStacktrace.add_argument( '--no-eager-stacktrace', action='store_const', const=False, dest='eager_stacktrace', help='print test errors after all tests have run') # Augment usage text to mention test filters and options passed to the VM usage = parser.format_usage().strip() if usage.startswith('usage: '): usage = usage[len('usage: '):] parser.usage = usage + ' [test filters...] [VM options...]' ut_args = [] delimiter = False # check for delimiter while len(args) > 0: arg = args.pop(0) if arg == '--': delimiter = True break ut_args.append(arg) if delimiter: # all arguments before '--' must be recognized parsed_args = parser.parse_args(ut_args) else: # parse all known arguments parsed_args, args = parser.parse_known_args(ut_args) # Remove junit_args values from parsed_args for a in junit_arg_actions: parsed_args.__dict__.pop(a.dest) if parsed_args.whitelist: try: with open(parsed_args.whitelist) as fp: parsed_args.whitelist = [ re.compile(fnmatch.translate(l.rstrip())) for l in fp.readlines() if not l.startswith('#') ] except IOError: mx.log('warning: could not read whitelist: ' + parsed_args.whitelist) if parsed_args.blacklist: try: with open(parsed_args.blacklist) as fp: parsed_args.blacklist = [ re.compile(fnmatch.translate(l.rstrip())) for l in fp.readlines() if not l.startswith('#') ] except IOError: mx.log('warning: could not read blacklist: ' + parsed_args.blacklist) if parsed_args.eager_stacktrace is None: junit_args.append('-JUnitEagerStackTrace') parsed_args.__dict__.pop('eager_stacktrace') _unittest(args, ['@Test', '@Parameters'], junit_args, **parsed_args.__dict__)
metavar='model_file', type=check_model, help='Vensim, Xmile or PySD model file') parser.add_argument('new_values', metavar='variable=new_value', type=split_vars, nargs='*', action=SplitVarsAction, help='redefine the value of variable with new value.' 'variable must be a model component, new_value can be a ' 'float or a a list of two list') # The destionation new_values2 will never used as the previous argument # is given also with nargs='*'. Nevertheless, the following variable # is declared for documentation parser.add_argument('new_values2', metavar='variable:initial_value', type=split_vars, nargs='*', action=SplitVarsAction, help='redefine the initial value of variable.' 'variable must be a model stateful element, initial_value' ' must be a float') ######### # Usage # ######### parser.usage = parser.format_usage().replace("usage: PySD", "python -m pysd")
def parseOptions(self, opts, nameSpace = None): parser = ArgumentParser() parser.add_argument('--x', dest = 'x', type = float, default = self.D_X) parser.add_argument('--granularity', dest = 'granularity', type = int, default = self.D_GRANULARITY) parser.add_argument('--random-metric-weight', dest = 'randomMetricWeight', type = float, default = self.D_RANDOM_METRIC_WEIGHT) parser.add_argument('--ip-metric-weight', dest = "ipMetricWeight", type = float, default = self.D_IP_METRIC_WEIGHT) parser.add_argument('--balanced-metric-weight', dest = 'balancedMetricWeight', type = float, default = self.D_BALANCED_METRIC_WEIGHT) parser.add_argument('--bucket-type', dest = 'bucket_type', choices = [self.PROBALISTIC_BUCKET, self.ORDERED_BUCKET, self.PROBALISTIC_POWER_BUCKET], default = self.D_BUCKET_TYPE) parser.add_argument('--sample-size', dest = 'sampleSize', type = float, default = self.D_SAMPLE_SIZE) parser.add_argument('--overlay-size', dest = 'overlay_size', type = int, default = self.D_OVERLAY_SIZE) try: if nameSpace is not None: self.options = argparse.Namespace( **vars(nameSpace) ) else: self.options = argparse.Namespace() self.options.bytesThreshold = self.D_BYTES_THRESHOLD self.options.maxRuns = self.D_MAX_RUNS parser.parse_args(opts, self.options) if self.options.randomMetricWeight > 0: self.metrics.append((self.options.randomMetricWeight, self.metricRandom)) if self.options.balancedMetricWeight > 0: self.metrics.append((self.options.balancedMetricWeight, self.metricBalance)) if self.options.ipMetricWeight > 0: self.metrics.append((self.options.ipMetricWeight, self.metricIp)) if self.options.bucket_type == self.PROBALISTIC_BUCKET: self.options.bucket = ProbabilisticBucket elif self.options.bucket_type == self.ORDERED_BUCKET: self.options.bucket = OrderedBucket elif self.options.bucket_type == self.PROBALISTIC_POWER_BUCKET: self.options.bucket = ProbabilisticPowerBucket self.D_X = self.options.x self.D_GRANULARITY = self.options.granularity self.D_RANDOM_METRIC_WEIGHT = self.options.randomMetricWeight self.D_IP_METRIC_WEIGHT = self.options.ipMetricWeight self.D_BALANCED_METRIC_WEIGHT = self.options.balancedMetricWeight self.D_BUCKET_TYPE = self.options.bucket_type self.D_SAMPLE_SIZE = self.options.sampleSize self.D_OVERLAY_SIZE = self.options.overlay_size print(self.options) except (SystemExit, ArgumentError): self.logger.error("Error while parsing options %s", parser.format_usage()) raise WatcherArgumentError(parser.format_usage())
if __name__ == "__main__": arg_parser = ArgumentParser() arg_parser.add_argument('-d', '--debug', help='prints stack trace for errors', action='store_true') arg_parser.add_argument('-t', '--tree', help='prints the abstract syntax tree', action='store_true') arg_parser.add_argument('-o', '--optimize', help='optimizes the emitted code', action='store_true') arg_parser.add_argument('-r', '--recompile', help='recompiles the standard library', action='store_true') arg_parser.add_argument('src', help='source file') arg_parser.add_argument('dest', help='destination file', nargs='?', default=None) args = arg_parser.parse_args() try: with open(args.src) as cmm_file: code = cmm_file.read() except OSError as e: print(e, file=sys.stderr) sys.exit(arg_parser.format_usage()) try: stdlib = load_stdlib() tokens = Lexer().tokenize(code) tree = Parser(tokens).parse(os.path.basename(args.src)) code = CodeGenerator(tree, stdlib).generate(args.optimize) if args.tree: print_tree(tree) if args.dest is None: print() if args.dest is not None: with open(args.dest, 'w') as out_file: out_file.write(code) else: print(code) except CompilerError as e:
def unittest(args, test_report_tags=None): """run the JUnit tests :param test_report_tags: in not None, key/value pairs that will be used to make a test report for the unit tests. See detail for `tags` parameter of `mx_gate.make_test_report` function. :return the generated test report iff `test_report_tags` is not None """ junit_arg_actions = [] junit_args = [] class MxJUnitWrapperArg(Action): def __init__(self, **kwargs): kwargs['required'] = False Action.__init__(self, **kwargs) junit_arg_actions.append(self) def __call__(self, parser, namespace, values, option_string=None): junit_args.append('-' + self.dest) junit_args.append(values) class MxJUnitWrapperBoolArg(Action): def __init__(self, **kwargs): kwargs['required'] = False kwargs['nargs'] = 0 Action.__init__(self, **kwargs) junit_arg_actions.append(self) def __call__(self, parser, namespace, values, option_string=None): junit_args.append('-' + self.dest) parser = ArgumentParser( prog='mx unittest', description='run the JUnit tests', formatter_class=RawDescriptionHelpFormatter, epilog=unittestHelpSuffix, ) parser.add_argument('--blacklist', help='run all testcases not specified in <file>', metavar='<file>') parser.add_argument('--whitelist', help='run testcases specified in <file> only', metavar='<file>') parser.add_argument('--verbose', help='enable verbose JUnit output', dest='JUnitVerbose', action=MxJUnitWrapperBoolArg) parser.add_argument('--very-verbose', help='enable very verbose JUnit output', dest='JUnitVeryVerbose', action=MxJUnitWrapperBoolArg) parser.add_argument( '--max-class-failures', help= 'stop after N test classes that have a failure (default is no limit)', type=is_strictly_positive, metavar='<N>', dest='JUnitMaxClassFailures', action=MxJUnitWrapperArg) parser.add_argument('--fail-fast', help='alias for --max-class-failures=1', dest='JUnitFailFast', action=MxJUnitWrapperBoolArg) parser.add_argument( '--enable-timing', help='enable JUnit test timing (requires --verbose/--very-verbose)', dest='JUnitEnableTiming', action=MxJUnitWrapperBoolArg) parser.add_argument( '--regex', help='run only testcases matching a regular expression', metavar='<regex>') parser.add_argument('--color', help='enable color output', dest='JUnitColor', action=MxJUnitWrapperBoolArg) parser.add_argument('--gc-after-test', help='force a GC after each test', dest='JUnitGCAfterTest', action=MxJUnitWrapperBoolArg) parser.add_argument( '--record-results', help='record test class results to passed.txt and failed.txt', dest='JUnitRecordResults', action=MxJUnitWrapperBoolArg) record_help_msg_shared = 'If <file> is "-", the tests will be printed to stdout. ' +\ 'In contrast to --record-results this prints not only the test class but also the test method.' parser.add_argument('--print-passed', metavar="<file>", dest='JUnitRecordPassed', action=MxJUnitWrapperArg, help='record passed test class results in <file>. ' + record_help_msg_shared) parser.add_argument('--print-failed', metavar="<file>", dest='JUnitRecordFailed', action=MxJUnitWrapperArg, help='record failed test class results in <file>. ' + record_help_msg_shared) parser.add_argument('--json-results', metavar="<file>", help='record test results in <file> in json format.') parser.add_argument('--suite', help='run only the unit tests in <suite>', metavar='<suite>') parser.add_argument('--repeat', help='run each test <n> times', dest='JUnitRepeat', action=MxJUnitWrapperArg, type=is_strictly_positive, metavar='<n>') parser.add_argument( '--open-packages', dest='JUnitOpenPackages', action=MxJUnitWrapperArg, metavar='<module>/<package>[=<target-module>(,<target-module>)*]', help= "export and open packages regardless of module declarations (see more detail and examples below)" ) eagerStacktrace = parser.add_mutually_exclusive_group() eagerStacktrace.add_argument( '--eager-stacktrace', action='store_const', const=True, dest='eager_stacktrace', help='print test errors as they occur (default)') eagerStacktrace.add_argument( '--no-eager-stacktrace', action='store_const', const=False, dest='eager_stacktrace', help='print test errors after all tests have run') for a, k in _extra_unittest_arguments: parser.add_argument(*a, **k) # Augment usage text to mention test filters and options passed to the VM usage = parser.format_usage().strip() if usage.startswith('usage: '): usage = usage[len('usage: '):] parser.usage = usage + ' [test filters...] [VM options...]' args, parsed_args = parse_split_args(args, parser, "--") # Remove junit_args values from parsed_args for a in junit_arg_actions: parsed_args.__dict__.pop(a.dest) if parsed_args.whitelist: try: with open(parsed_args.whitelist) as fp: parsed_args.whitelist = [ re.compile(fnmatch.translate(l.rstrip())) for l in fp.readlines() if not l.startswith('#') ] except IOError: mx.log('warning: could not read whitelist: ' + parsed_args.whitelist) if parsed_args.blacklist: try: with open(parsed_args.blacklist) as fp: parsed_args.blacklist = [ re.compile(fnmatch.translate(l.rstrip())) for l in fp.readlines() if not l.startswith('#') ] except IOError: mx.log('warning: could not read blacklist: ' + parsed_args.blacklist) if parsed_args.eager_stacktrace is None: junit_args.append('-JUnitEagerStackTrace') parsed_args.__dict__.pop('eager_stacktrace') make_test_report = test_report_tags is not None test_results = parsed_args.__dict__.pop('json_results') delete_test_results = False if not test_results and make_test_report: test_results = tempfile.NamedTemporaryFile(delete=False, suffix='.json.gz').name delete_test_results = True if test_results: junit_args.append('-JUnitJsonResults') junit_args.append(test_results) try: _unittest(args, ['@Test', '@Parameters'], junit_args, **parsed_args.__dict__) if make_test_report: import mx_gate return mx_gate.make_test_report(test_results, tags=test_report_tags) finally: if delete_test_results: os.unlink(test_results)
def __init__(self): parser = ArgumentParser( description='Add/update a Symbolic Partner Name in tomnt.ini.', formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("iniFileName", help="filename to edit") parser.add_argument("-s", "--SPN", help="partner/SPN name to update/create", required=True) parser.add_argument("--hostname", help="partner DNSName") parser.add_argument("-i", "--ip", help="partner IP address") parser.add_argument("-p", "--port", help="partner tcp port", required=True) parser.add_argument("--SSL", help="SSL parameters to use in case of SSL.") parser.add_argument("-l", "--label", help="label of the SPN") parser.add_argument("--variables", help="variables of the SPN.") parser.add_argument("-t", "--table", help="PeSIT table.", required=True) parser.add_argument("-nb", "--nbSessions", help="Number of simultaneous sessions.", required=True) parser.add_argument("--no-backup", help="don't backup the original file", action='store_true', default=False) parser.add_argument("-y", "--run", default=False, action='store_true', help="run in real mode.") args = parser.parse_args() self.iniFileName = args.iniFileName self.SPN = args.SPN if not args.ip and not args.hostname: print >> stderr, "ERROR: You have to define either the SPN DNSName or IP address." print >> stderr, "\n" + parser.format_usage() exit(1) self.hostname = args.hostname self.ip = args.ip self.port = args.port self.SSL = args.SSL self.label = args.label self.table = args.table self.variables = args.variables self.nbSessions = args.nbSessions self.scriptBaseName = parser.prog self.no_backup = args.no_backup self.run = args.run
help='Restrict operations to dependencies of this type') parser.add_argument('-o', '--outfile', dest='outfile', type=str, default='', metavar='<outfile>', help='File to write results to') parser.add_argument('--no-header', dest='no_header', default=False, action='store_true', help='No export header') parser.add_argument('command', metavar='<command>', choices=['satisfy', 'validate', 'export', 'version'], help="'satisfy' satisfies the dependcies specified in " "<depfile>. 'validate' only validates <depfile> and does " "not perform any system operations. 'export' exports " "requirements to a specified file (using -o)") parser.add_argument('context', metavar='<context>', type=str, default='all', nargs='?', help='The dependency context to perform <command> on') USAGE = parser.format_usage().strip() #------------------------------------------------------------------------------- # Dispatch type def dispatch_type(typ): if typ == 'all': return AnyType() if ',' in typ: return Type.dispatch(tuple([dispatch_type(t) for t in typ.split(',')])) if typ in DEPENDENCY_KEYS: return Type.dispatch(DEPENDENCY_KEYS[typ]) raise TypeError("Unknown type: {}".format(typ)) #------------------------------------------------------------------------------- # Dispatch outfile
def main(): parser = ArgumentParser(description='Convert kaldi data directory to uem dat files', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--verbose', type=int, \ dest='verbose', default=0, \ help='Give higher verbose for more logging') parser.add_argument('--get-text', action='store_true', \ help='Get text in dat file') parser.add_argument('--prefix', type=str, \ help='Add db file name as db-<prefix>-{utt/spk}.dat') parser.add_argument('kaldi_dir', \ help='Kaldi data directory') parser.add_argument('output_dir', \ help='Directory to store uem dat files') parser.usage=':'.join(parser.format_usage().split(':')[1:]) \ + 'e.g. : %(prog)s --prefix 203-lao-v0 data/dev10h.seg CMU_db' options = parser.parse_args() if options.get_text: try: text_file = open(options.kaldi_dir+'/text', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/text')) sys.exit(1) try: segments_file = open(options.kaldi_dir+'/segments', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/segments')) sys.exit(1) try: scp_file = open(options.kaldi_dir+'/wav.scp', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/wav.scp')) sys.exit(1) reco2file_map = {} for line in scp_file.readlines(): splits = line.strip().split() m = re.search(r".*/(?P<file_name>[0-9A-Za-z_]*\.(sph|wav)).*", line) if not m: sys.stderr.write("%s does not contain a valid speech file (.wav or .sph)\n" % line.strip()) sys.exit(1) reco2file_map[splits[0]] = m.group('file_name') # End for spk2utt_map = {} if options.prefix == None: prefix = options.kaldi_dir.split('/')[-1].split('.')[0] else: prefix = options.prefix try: utt_dat = open(options.output_dir+'/db-'+prefix+'-utt.dat', 'w') spk_dat = open(options.output_dir+'/db-'+prefix+'-spk.dat', 'w') except IOError as e: repr(e) sys.stderr.write("%s: Could not write dat files in %s\n" % (sys.argv[0], options.output_dir)) sys.exit(1) for line in segments_file.readlines(): utt_id, file_id, start, end = line.strip().split() if (options.get_text): splits = text_file.readline().split() while splits[0] < utt_id: splits = text_file.readline().split() text = ' '.join(splits[1:]) else: text = "" utt_dat.write("{UTTID %s} {UTT %s} {SPK %s} {FROM %s} {TO %s} {TEXT %s}\n" % (utt_id, utt_id, file_id, start, end, text)) spk2utt_map.setdefault(file_id, []) spk2utt_map[file_id].append(utt_id) for spk, utts in list(spk2utt_map.items()): try: spk_dat.write("{SEGS %s} {ADC %s} {CONV %s.wav} {CHANNEL 1} {DUR }\n" % (' '.join(utts), reco2file_map[spk], spk)) except KeyError as e: repr(e) sys.stderr.write("%s: Error in getting file for %s\n" % (sys.argv[0], spk)) sys.exit(1) # End for segments_file.close() utt_dat.close() spk_dat.close()
from argparse import ArgumentParser __version__ = '0.1' parser = ArgumentParser(version=__version__) parser.add_argument("args", nargs="*") parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") __doc__ = '\n'.join([parser.format_usage(), parser.format_help()]) if __name__ == '__main__': args = parser.parse_args() print args, args.filename, args.args
def _parse_cmdline(args): p = ArgumentParser(description='Extract and convert DWC patient data.', fromfile_prefix_chars='@') g = p.add_argument_group('input selection') g.add_argument('--server', metavar='NAME', help='name of DWC database server') g.add_argument('--password-file', metavar='FILE', default='server.conf', help='file containing login credentials') g = p.add_argument_group('output database location') g.add_argument('--output-dir', metavar='DIR', help='directory to store output database') g.add_argument('--state-dir', metavar='DIR', help='directory to store state files') g = p.add_argument_group('conversion modes') g.add_argument('--init', action='store_true', help='initialize a new output database') g.add_argument('--batch', action='store_true', help='process available data and exit') g.add_argument('--live', action='store_true', help='collect data continuously') g.add_argument('--start', metavar='TIME', type=_parse_timestamp, help='begin collecting data at the given time') g.add_argument('--end', metavar='TIME', type=_parse_timestamp, help='collect data up to the given time') g.add_argument('--terminate', action='store_true', help='handle final data after permanent shutdown') opts = p.parse_args(args) progname = sys.argv[0] if opts.output_dir is None: sys.exit(('%s: no --output-dir specified' % progname) + '\n' + p.format_usage()) if opts.server is None: sys.exit(('%s: no --server specified' % progname) + '\n' + p.format_usage()) if (opts.init + opts.batch + opts.live) != 1: sys.exit( ('%s: must specify exactly one of --init, --batch, or --live' % progname) + '\n' + p.format_usage()) if opts.start is not None and not opts.init: sys.exit(('%s: --start can only be used with --init' % progname) + '\n' + p.format_usage()) if opts.end is not None and not opts.batch: sys.exit(('%s: --end can only be used with --batch' % progname) + '\n' + p.format_usage()) if opts.state_dir is None: opts.state_dir = opts.output_dir if opts.init: if os.path.exists(opts.state_dir): sys.exit("%s: directory %s already exists" % (progname, opts.state_dir)) if os.path.exists(opts.output_dir): sys.exit("%s: directory %s already exists" % (progname, opts.state_dir)) else: if not os.path.isdir(opts.state_dir): sys.exit("%s: directory %s does not exist" % (progname, opts.state_dir)) if not os.path.isdir(opts.output_dir): sys.exit("%s: directory %s does not exist" % (progname, opts.state_dir)) return opts
def _get_options(self, args): parser = ArgumentParser(description='A static site generator.') subparsers = parser.add_subparsers() parser.add_argument('-V', '--version', action='version', version='%(prog)s v{0}'.format(__version__), help="Prints %(prog)s's version and exits") log_level = parser.add_mutually_exclusive_group() log_level.add_argument('-l', '--log-level', default='INFO', type=str.upper, choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], help="Sets %(prog)s's log level") log_level.add_argument('-q', '--quiet', action='store_const', const='ERROR', dest='log_level', help="Sets %(prog)s's log level to ERROR") log_level.add_argument('-v', '--verbose', action='store_const', const='DEBUG', dest='log_level', help="Sets %(prog)s's log level to DEBUG") generate = subparsers.add_parser('generate', aliases=['gen', 'g'], help='Generates a static website') generate.add_argument( '--base-url', default=self.defaults['base_url'], help='Overrides the base URL configuration option') generate.add_argument('--locale', default=self.defaults['locale'], help='Sets the renderer locale') generate.add_argument('source', nargs='?', default='.', help='Location of the %(prog)s website') generate.add_argument( 'destination', help='Location to output the generated static website') generate.set_defaults(command=self.generate) force = generate.add_mutually_exclusive_group() force.add_argument( '-d', '--delete', action='store_true', help='Forces generation by DELETING the destination directory') force.add_argument( '-f', '--force', action='store_true', help='Forces generation by EMPTYING the destination directory') initialize = subparsers.add_parser( 'initialize', aliases=['init', 'i'], help='Creates a new %(prog)s website') initialize.add_argument( '--bare', action='store_true', help='Creates a new %(prog)s website without a theme') initialize.add_argument( '-d', '--delete', action='store_true', help='Forces creation by DELETING the destination directory') initialize.add_argument('-t', '--theme', default='dark', help='Sets the %(prog)s website theme') initialize.add_argument('destination', help='Location to output the %(prog)s website') initialize.set_defaults(command=self.initialize) serve = subparsers.add_parser( 'serve', aliases=['s'], help='Starts a local server to host the static website') serve.add_argument('--base-url', default=self.defaults['base_url'], help='Overrides the base URL configuration option') serve.add_argument('-p', '--port', default=8080, type=int, help='Sets the port the server will listen on') serve.add_argument('source', nargs='?', default='.', help='Location of the static website') serve.set_defaults(command=self.serve) watch = subparsers.add_parser( 'watch', aliases=['w'], help='Regenerates a %(prog)s website when changes occur') watch.add_argument('--base-url', default=self.defaults['base_url'], help='Overrides the base URL configuration option') watch.add_argument( '-f', '--force', action='store_true', help='Forces watching by EMPTYING the destination directory') watch.add_argument('--locale', default=self.defaults['locale'], help='Sets the renderer locale') watch.add_argument('source', nargs='?', default='.', help='Location of the %(prog)s website') watch.add_argument( 'destination', help='Location to output the generated static website') watch.set_defaults(command=self.watch) options = {} for name, value in vars(parser.parse_args(args)).items(): if value is None: continue options[name] = value if 'command' not in options: raise OptionException('Unknown command or option', parser.format_usage()) return options
def md_help(parser: _argparse.ArgumentParser) -> None: """ Args: parser: parser object Returns: """ if parser.prog is None: logging.info("Saving as foo.md") mdFile = MdUtils(file_name="foo") else: mdFile = MdUtils(file_name=os.path.splitext(parser.prog)[0], title=parser.prog) if parser.description: mdFile.new_header(level=1, title="Description") mdFile.new_paragraph(parser.description) if parser.epilog: mdFile.new_header(level=1, title="Epilog") mdFile.new_paragraph(parser.epilog) mdFile.new_header(level=1, title="Usage:") mdFile.insert_code(parser.format_usage(), language="bash") used_actions = {} options = ["short", "long", "default", "help"] i = 0 for k in parser._option_string_actions: action = parser._option_string_actions[k] list_of_str = ["", "", "", action.help] this_id = id(action) if this_id in used_actions: continue used_actions[this_id] = True for opt in action.option_strings: # --, long option if len(opt) > 1 and opt[1] in parser.prefix_chars: list_of_str[1] = inline_code(opt) # short opt elif len(opt) > 0 and opt[0] in parser.prefix_chars: list_of_str[0] = inline_code(opt) if not (isinstance(action.default, bool) or isinstance(action, _argparse._VersionAction) or isinstance(action, _argparse._HelpAction)): default = (action.default if isinstance(action.default, str) else repr(action.default)) list_of_str[2] = inline_code(default) options.extend(list_of_str) i += 1 mdFile.new_header(level=1, title="Arguments") mdFile.new_table( columns=4, rows=len(options) // 4, text=options, text_align="center", ) mdFile.create_md_file()
# Positional args add_argument(parser, 'task', metavar='<task>', type=str, default='', nargs='?', help='The task to run') add_argument(parser, 'args', metavar='ARGS', nargs='*', help='Additional arguments for the task') USAGE = parser.format_usage().strip() OPTION_STRINGS.sort() #------------------------------------------------------------------------------- def print_(s, flush=True): sys.stdout.write(s + '\n') if flush: sys.stdout.flush() #------------------------------------------------------------------------------- # Yatrfile search YATRFILE_PATTERN = re.compile('^[Yy]atrfile(.yml)?$')