Python argparse._ Examples
The following are 17 code examples for showing how to use argparse._(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
argparse
, or try the search function
.
Example 1
Project: deepbgc Author: Merck File: main.py License: MIT License | 6 votes |
def main(argv=None): print(""" _____ ____ ____ ____ | _ \ ___ ___ ____ | __ ) / ___) / ___) | | \ \/ _ \/ _ \ _ \| _ \ | | _ | | | |_/ / __/ __/ |_) | |_) || |_| || |___ |____/ \___|\___| ___/|____/ \____| \____) =================|_|===== version """ + __version__ + " =====", file=sys.stderr) try: run(argv) except KeyboardInterrupt: print(' Interrupted by the user') sys.exit(0) except Exception as e: message = e.args[0] if e.args else '' logging.exception(message) logging.error('='*80) logging.error('DeepBGC failed with %s%s', type(e).__name__, ': {}'.format(message) if message else '') if len(e.args) > 1: logging.error('='*80) for arg in e.args[1:]: logging.error(arg) logging.error('='*80) exit(1)
Example 2
Project: aptsources-cleanup Author: davidfoerster File: zip.py License: MIT License | 6 votes |
def _parse_handle_files(self, ns): if not all(ns.files): self.error(_("Invalid path") + ": ''") if ns.names_file is not None: assert ns.names_file0 is None names_file = ns.names_file delim = names_file.newlines assert delim != "" elif ns.names_file0 is not None: names_file = ns.names_file0 delim = "\0" else: names_file = None del ns.names_file, ns.names_file0 if names_file is not None: with names_file: ns.files.extend(filter(None, getlines(names_file, delim))) if not ns.files: self.error(_("No files to add to the archive."))
Example 3
Project: calmjs Author: calmjs File: argparse.py License: GNU General Public License v2.0 | 5 votes |
def error(self, message): if message != _('too few arguments'): super(ArgumentParser, self).error(message)
Example 4
Project: calmjs Author: calmjs File: argparse.py License: GNU General Public License v2.0 | 5 votes |
def soft_error(self, message): """ Same as error, without the dying in a fire part. """ self.print_usage(sys.stderr) args = {'prog': self.prog, 'message': message} self._print_message( _('%(prog)s: error: %(message)s\n') % args, sys.stderr)
Example 5
Project: calmjs Author: calmjs File: argparse.py License: GNU General Public License v2.0 | 5 votes |
def unrecognized_arguments_error(self, args): self.soft_error(_('unrecognized arguments: %s') % ' '.join(args))
Example 6
Project: calmjs Author: calmjs File: test_argparse.py License: GNU General Public License v2.0 | 5 votes |
def test_error(self): stub_stdouts(self) parser = ArgumentParser() parser.error(_('too few arguments')) self.assertEqual('', sys.stdout.getvalue()) self.assertEqual('', sys.stderr.getvalue())
Example 7
Project: streamlink Author: streamlink File: argparser.py License: BSD 2-Clause "Simplified" License | 5 votes |
def _match_argument(self, action, arg_strings_pattern): # - https://github.com/streamlink/streamlink/issues/971 # - https://bugs.python.org/issue9334 # match the pattern for this action to the arg strings nargs_pattern = self._get_nargs_pattern(action) match = argparse._re.match(nargs_pattern, arg_strings_pattern) # if no match, see if we can emulate optparse and return the # required number of arguments regardless of their values if match is None: nargs = action.nargs if action.nargs is not None else 1 if isinstance(nargs, numbers.Number) and len(arg_strings_pattern) >= nargs: return nargs # raise an exception if we weren't able to find a match if match is None: nargs_errors = { None: argparse._('expected one argument'), argparse.OPTIONAL: argparse._('expected at most one argument'), argparse.ONE_OR_MORE: argparse._('expected at least one argument'), } default = argparse.ngettext('expected %s argument', 'expected %s arguments', action.nargs) % action.nargs msg = nargs_errors.get(action.nargs, default) raise argparse.ArgumentError(action, msg) # return the number of arguments matched return len(match.group(1))
Example 8
Project: trains-agent Author: allegroai File: __main__.py License: Apache License 2.0 | 5 votes |
def main(): parser = get_parser() args = parser.parse_args() try: command_name = args.command if not command_name: return parser.print_help() except AttributeError: parser.error(argparse._('too few arguments')) return run_command(parser, args, command_name)
Example 9
Project: trains-agent Author: allegroai File: base.py License: Apache License 2.0 | 5 votes |
def error(self, message): if self._usage_on_error and message == argparse._('too few arguments'): self.print_help() print() self.exit(2, argparse._('%s: error: %s\n') % (self.prog, message)) super(Parser, self).error(message)
Example 10
Project: trains-agent Author: allegroai File: base.py License: Apache License 2.0 | 5 votes |
def hyphenate(s): return s.replace('_', '-')
Example 11
Project: deepbgc Author: Merck File: main.py License: MIT License | 5 votes |
def parse_args(self, args=None, namespace=None): args, argv = self.parse_known_args(args, namespace) if argv: message = argparse._('unrecognized arguments: %s') % ' '.join(argv) if hasattr(args, 'cmd') and args.cmd: # Show help for specific command, catch exit and print message try: super(DeepBGCParser, self).parse_args(args=[args.cmd, '--help']) except: pass self.exit(2, "{}\n{}\n".format("="*80, message)) return args
Example 12
Project: aptsources-cleanup Author: davidfoerster File: __main__.py License: MIT License | 5 votes |
def load_sources_dir(sourceslist, dirname): if not os.path.isdir(dirname): termwrap.stderr().print(': '.join( (_('Error'), _('No such directory'), dirname))) return 1 import glob sourceslist.list.clear() foreach(sourceslist.load, glob.iglob(os.path.join(dirname, "**/*.list"), recursive=True)) return 0
Example 13
Project: aptsources-cleanup Author: davidfoerster File: __main__.py License: MIT License | 5 votes |
def __init__(self, option_strings, version=None, dest=argparse.SUPPRESS, default=argparse.SUPPRESS, help=None ): if help is None: help = _("Show program's version number and exit.") super().__init__(option_strings, dest, 0, help=help) self.version = version
Example 14
Project: aptsources-cleanup Author: davidfoerster File: zip.py License: MIT License | 5 votes |
def _parse_handle_executable(self, ns): if ns.executable is NotImplemented: refname = "sys.executable" self.error( _("Unable to determine a default interpreter from the runtime " "environment ({:s}={!r}). Please specify it explicitly.") .format(refname, eval(refname)))
Example 15
Project: aptsources-cleanup Author: davidfoerster File: __main__.py License: MIT License | 4 votes |
def handle_duplicates(sourceslist, apply_changes=None, equivalent_schemes=None ): """Interactive disablement of duplicate source entries""" stdout = termwrap.stdout() stdout_indent1 = stdout.copy( subsequent_indent=stdout.subsequent_indent + ' ' * 4) stdout_indent2 = stdout_indent1.copy( initial_indent=stdout_indent1.subsequent_indent) duplicates = tuple(get_duplicates( sourceslist, equivalent_schemes=equivalent_schemes)) if duplicates: for dupe_set in duplicates: dupe_set = iter( sort_dupe_set_by_scheme_class(equivalent_schemes, dupe_set)) orig = next(dupe_set) for dupe in dupe_set: stdout.print(_('Overlapping source entries:')) for i, se in enumerate((orig, dupe), 1): stdout_indent1.print( _("{ordinal:2d}. file {file!r}:") .format(ordinal=i, file=se.file)) stdout_indent2.print(se.line) stdout.print(_("I disabled all but the first entry."), end="\n\n") dupe.disabled = True stdout.print( _N('{nduplicates:d} source entry was disabled', '{nduplicates:d} source entries were disabled', len(duplicates)).format(nduplicates=len(duplicates)) + ':') stdout_indent2.initial_indent = stdout_indent2.initial_indent[:-2] stdout_indent2.print_all(map(str, itertools.chain(*duplicates)), sep='\n') if apply_changes is None: stdout.file.write('\n') answer = ( Choices(_U('yes'), _U('no'), default='no') .ask(_('Do you want to save these changes?'))) apply_changes = answer is not None and answer.orig == 'yes' if not apply_changes: termwrap.stderr().print(_('Aborted.')) return 2 if apply_changes: sourceslist.save() else: stdout.print(_('No duplicate entries were found.')) return 0
Example 16
Project: aptsources-cleanup Author: davidfoerster File: __main__.py License: MIT License | 4 votes |
def handle_empty_files(sourceslist): """Interactive removal of sources list files without valid enabled entries""" rv = 0 total_count = 0 removed_count = 0 stdout = termwrap.stdout() choices = Choices( _U('yes'), _U('no'), _U('all'), _U('none'), _U('display'), default='no') on_eof = choices.orig['none'] answer = None for total_count, source_entries in enumerate(get_empty_files(sourceslist), 1): file = source_entries[0].file while answer is None: stdout.file.write('\n') stdout.print( _("'{file:s}' contains no valid and enabled repository lines.") .format(file=file)) answer = choices.ask(_('Do you want to remove it?'), on_eof=on_eof) if answer is not None and answer.orig == 'display': display_file(file) answer = None if answer.orig in ('yes', 'all'): rv2, rc2 = remove_sources_files(file) rv |= rv2 if rc2: removed_count += rc2 foreach(sourceslist.remove, source_entries) if answer.orig not in ('all', 'none'): answer = None if total_count: stdout.file.write('\n') stdout.print( _('{nremoved:d} of {ntotal:d} empty sourcelist files removed.') .format(nremoved=removed_count, ntotal=total_count)) return rv
Example 17
Project: aptsources-cleanup Author: davidfoerster File: zip.py License: MIT License | 4 votes |
def main(args=None): with ArgumentParser() as ap: args = ap.parse_args(args) quiet = args.quiet archive = args.archive directory = args.directory follow_symlinks = not args.symlinks if args.executable: shebang = args.executable.join((b"#!", b"\n")) archive.fp.write(shebang) archive.start_dir += len(shebang) del shebang if not quiet: s_bytes = _("bytes") print( _("Compressing files into {:s}").format(archive.fp.name), end=":\n\n") success = 0 for file in args.files: try: info = archive.write( file, dir_fd=directory, follow_symlinks=follow_symlinks) except EnvironmentError as ex: print(ex, file=sys.stderr) else: success += 1 if not quiet: print( "{:s} => {:s} ({:4.0%})".format( format_size(info.file_size), format_size(info.compress_size), not info.file_size or info.compress_size / info.file_size), file, sep=" ") main_py = "__main__.py" if args.executable and main_py not in archive.NameToInfo: print( _("Warning: Executable Python ZIP archives require a file {!r} in the " "archive root directory to work but you omitted it.") .format(main_py), file=sys.stderr) if success: print("", _("Everything is OK."), sep="\n") return not success