我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用argparse.RawDescriptionHelpFormatter()。
def get_argument_parser(): from argparse import ArgumentParser, RawDescriptionHelpFormatter from CallerLookup.Strings import CallerLookupArgParserHelp as s parser = ArgumentParser(description=s.DESCRIPTION, formatter_class=RawDescriptionHelpFormatter) for entry in __VALID_ARGUMENTS: arg_default_value = __DEFAULT_ARGS[entry] if entry in __DEFAULT_ARGS else None parser.add_argument("--{0}".format(__ARG_KEYS[entry][0]), metavar=__ARG_KEYS[entry][1].upper(), dest=entry, type=type(arg_default_value) if arg_default_value else None, help=getattr(s, entry, "") + ( " (Default: {0})".format(arg_default_value) if arg_default_value else ""), default=arg_default_value, required=False) return parser
def parse_command_line(): # Define parameters parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="SAM - Discard duplicates/multiple-mappers", version=version_info, epilog=""" This script reads a SAM file, and discards ALL reads which map multiple times (does not keep even one of the mapping locations). TODO: Explain hard-clipped reads in minION runs Example: # Remove all duplicated reads dirnames: $ %(prog)s input.sam > output.no-dups.sam """) # Positional parameter parser.add_argument('filename', metavar='FILE', help='file to process'); args = parser.parse_args() return args
def main(): parser = argparse.ArgumentParser(description=help_msg( ), formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-v', '--version', help='Show the version and exit', action="store_true") parser.add_argument( '-d', '--debug', help='Increase verbosity to ease debugging process', action="store_true") parser.add_argument('-t', '--tree', nargs=1, dest='acbs_tree', help='Specify which abbs-tree to use') parser.add_argument('packages', nargs='*', help='Packages to be built') args = parser.parse_args() if args.version: print('ACBS version {}'.format(acbs_version)) if len(args.packages) > 0: if args.acbs_tree is not None: init_env(args.acbs_tree) else: init_env() sys.exit(build_pkgs(args.packages))
def main(): parser = argparse.ArgumentParser(description=_description(), formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-l', '--list', action='store_true') parser.add_argument('-p', '--password') parser.add_argument('-t', '--target-dir') parser.add_argument('IN', type=AndroidBackup) args = parser.parse_args() with args.IN as infile: if args.list: infile.list( password=args.password ) else: infile.unpack( target_dir=args.target_dir, password=args.password )
def main(): parser = argparse.ArgumentParser(description=_description(), formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('OUT') parser.add_argument('-p', '--password') parser.add_argument('-s', '--source-dir') parser.add_argument('-e', '--encrypt', action='store_true') args = parser.parse_args() ab = android_backup.AndroidBackup() ab.version = 3 ab.compression = android_backup.CompressionType.ZLIB ab.encryption = android_backup.EncryptionType.NONE if args.encrypt: ab.encryption = android_backup.EncryptionType.AES256 ab.pack( fname=args.OUT, source_dir=args.source_dir, password=args.password )
def doArchive(argv, bobRoot): subHelp = "\n ... ".join(sorted( [ "{:8} {}".format(c, d[1]) for (c, d) in availableArchiveCmds.items() ])) parser = argparse.ArgumentParser(prog="bob archive", formatter_class=argparse.RawDescriptionHelpFormatter, description="""Manage binary artifacts archive. The following subcommands are available: bob archive {} """.format(subHelp)) parser.add_argument('subcommand', help="Subcommand") parser.add_argument('args', nargs=argparse.REMAINDER, help="Arguments for subcommand") args = parser.parse_args(argv) if args.subcommand in availableArchiveCmds: availableArchiveCmds[args.subcommand][0](args.args) else: parser.error("Unknown subcommand '{}'".format(args.subcommand))
def main(argv=None): if argv is None: argv = sys.argv parser = ArgumentParser('Level GPS phase to code.', formatter_class=RawDescriptionHelpFormatter, epilog=get_epilog()) parser.add_argument('leveled_arc_h5_fname', type=str, help='output H5 file containing leveled phase arcs') parser.add_argument('phase_edit_h5_fname', type=str, help='input H5 file generated by pyrsss.gps.phase_edit') parser.add_argument('--config', '-c', type=str, nargs='+', default=[], help='leveling configuration overrides (specify as, e.g., minimum_elevation=15)') args = parser.parse_args(argv[1:]) level_process(args.leveled_arc_h5_fname, args.phase_edit_h5_fname, config_overrides=args.config)
def main(): parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent(''' CWL generator - Create GGR CWL workflows using templates -------------------------------------------------------- ''')) # Base script options parser.add_argument('-o', '--outdir', metavar='output_dir', dest='outdir', type=str, help='Output directory where the files will be placed.') parser.add_argument('-c', '--config-yaml', dest='config_yaml', required=True, help='Config file used while rendering the CWL file.') # Parse input args = parser.parse_args() if args.outdir and not os.path.isdir(args.outdir): os.mkdir(args.outdir) # Generate outputs render_cwl_from_yaml(args.config_yaml, args.outdir)
def add_subparser(subparsers): _parser = subparsers.add_parser("houston", description="QuantRocket Houston API Gateway CLI", help="quantrocket houston -h") _subparsers = _parser.add_subparsers(title="subcommands", dest="subcommand") _subparsers.required = True examples = """ Ping houston. Examples: quantrocket houston ping """ parser = _subparsers.add_parser( "ping", help="ping houston", epilog=examples, formatter_class=argparse.RawDescriptionHelpFormatter) parser.set_defaults(func="quantrocket.houston._cli_ping")
def add_subparser(subparsers): _parser = subparsers.add_parser("license", description="QuantRocket license service CLI", help="quantrocket license -h") _subparsers = _parser.add_subparsers(title="subcommands", dest="subcommand") _subparsers.required = True examples = """ Return the current license profile. Examples: View the current license profile: quantrocket license get """ parser = _subparsers.add_parser( "get", help="return the current license profile", epilog=examples, formatter_class=argparse.RawDescriptionHelpFormatter) parser.set_defaults(func="quantrocket.license._cli_get_license_profile")
def main(): parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__) parser.add_argument("input", help="XML wiki dump file") parser.add_argument("--id", default="", help="article number, or range first-last") parser.add_argument("--template", action="store_true", help="extract also all templates") parser.add_argument("-v", "--version", action="version", version='%(prog)s ' + version, help="print program version") args = parser.parse_args() process_data(args.input, args.id, args.template)
def __init__(self, wmclass): Gtk.Window.__init__(self) OSDWindow._apply_css(Config()) self.argparser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog=self.EPILOG) self._add_arguments() self.exit_code = -1 self.position = (20, -20) self.mainloop = None self._controller = None self.set_name(wmclass) self.set_wmclass(wmclass, wmclass) self.set_decorated(False) self.stick() self.set_skip_taskbar_hint(True) self.set_skip_pager_hint(True) self.set_keep_above(True) self.set_type_hint(Gdk.WindowTypeHint.NOTIFICATION)
def parse_args(self, method, args): # create an argument parser parser = ArgumentParser(prog=method.__name__, description=dedent(method.__doc__ or ''), formatter_class=RawDescriptionHelpFormatter) # Add method options to the subparser for opt in method.options: parser.add_argument(*opt.args, **opt.kwargs) # Add global options to the subparser if hasattr(self, 'globals'): for opt in self.globals: parser.add_argument(*opt.args, **opt.kwargs) results = {} args = vars(parser.parse_args(args)) # Convert dashes to underscore for key, value in args.items(): results[re.sub('-', '_', key)] = value return results
def parseOptions(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("inputpath", help="input.wmf file") parser.add_argument("outputbase", nargs='?', default=None, help="output base filename, defaults to input[.svg|.png]") parser.add_argument("-c", "--compress", action="store_true", default=False, help="compress SVG") parser.add_argument("-r", "--remove", action="store_true", default=False, help="remove input.wmf after conversion") parser.add_argument("-v", "--verbose", action="store_true", default=False, help="report written file type and path") parser.add_argument('-V', '--version', action='version', version="%(prog)s (" + __version__ + ")") parser.add_argument("--with-wmf2svg", default=WMF2SVG, help="path to 'wmf2svg.jar' binary") args = vars(parser.parse_args()) if not args["outputbase"]: args["outputbase"] = os.path.splitext(args["inputpath"])[0] return args
def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="learn BPE-based word segmentation") parser.add_argument( '--input', '-i', type=argparse.FileType('r'), default=sys.stdin, metavar='PATH', help="Input text (default: standard input).") parser.add_argument( '--output', '-o', type=argparse.FileType('w'), default=sys.stdout, metavar='PATH', help="Output file for BPE codes (default: standard output)") parser.add_argument( '--symbols', '-s', type=int, default=10000, help="Create this many new symbols (each representing a character n-gram) (default: %(default)s))") parser.add_argument( '--verbose', '-v', action="store_true", help="verbose mode.") parser.add_argument('--min-freq', '-f', type=int, default=2, help="minimum word frequency") return parser
def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="learn BPE-based word segmentation") parser.add_argument( '--input', '-i', type=argparse.FileType('r'), default=sys.stdin, metavar='PATH', help="Input file (default: standard input).") parser.add_argument( '--codes', '-c', type=argparse.FileType('r'), metavar='PATH', required=True, help="File with BPE codes (created by learn_bpe.py).") parser.add_argument( '--output', '-o', type=argparse.FileType('w'), default=sys.stdout, metavar='PATH', help="Output file (default: standard output)") parser.add_argument( '--separator', '-s', type=str, default='@@', metavar='STR', help="Separator between non-final subword units (default: '%(default)s'))") return parser
def main(): """Intera RSDK Joint Velocity Example: Wobbler Commands joint velocities of randomly parameterized cosine waves to each joint. Demonstrates Joint Velocity Control Mode. """ arg_fmt = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(formatter_class=arg_fmt, description=main.__doc__) parser.parse_args(rospy.myargv()[1:]) print("Initializing node... ") rospy.init_node("rsdk_joint_velocity_wobbler") wobbler = Wobbler() rospy.on_shutdown(wobbler.clean_shutdown) wobbler.wobble() print("Done.")
def main(): """RSDK Head Example: Wobbler Nods the head and pans side-to-side towards random angles. Demonstrates the use of the intera_interface.Head class. """ arg_fmt = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(formatter_class=arg_fmt, description=main.__doc__) parser.parse_args(rospy.myargv()[1:]) print("Initializing node... ") rospy.init_node("rsdk_head_wobbler") wobbler = Wobbler() rospy.on_shutdown(wobbler.clean_shutdown) print("Wobbling... ") wobbler.wobble() print("Done.")
def register_args(subparsers): class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter): def _format_action(self, action): parts = super()._format_action(action) if action.nargs == argparse.PARSER: parts = "\n".join([line for line in parts.split("\n")[1:]]) parts += "\n\nSpider safely!" return parts parser = subparsers.add_parser(name='observe', help="Passively observe network traffic", formatter_class=SubcommandHelpFormatter) parser.add_argument('--list-chains', help="Prints a list of available chains", action='store_true') parser.add_argument('-i', '--interface', default="eth0", help="The interface to use for the observer. (Default: eth0)") parser.add_argument('--output', default='/dev/stdout', metavar='OUTPUTFILE', help=("The file to output results data to. " "Defaults to standard output.")) parser.add_argument('chains', nargs='*', help="Observer chains to use") # Set the command entry point parser.set_defaults(cmd=run_observer)
def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="learn BPE-based word segmentation") parser.add_argument( '--input', '-i', type=argparse.FileType('r'), default=sys.stdin, metavar='PATH', help="Input text (default: standard input).") parser.add_argument( '--output', '-o', type=argparse.FileType('w'), default=sys.stdout, metavar='PATH', help="Output file for BPE codes (default: standard output)") parser.add_argument( '--symbols', '-s', type=int, default=10000, help="Create this many new symbols (each representing a character n-gram) (default: %(default)s))") parser.add_argument( '--verbose', '-v', action="store_true", help="verbose mode.") return parser
def main(argv, wayout): if not len(argv): argv.append('-h') parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__) parser.add_argument("-a","--alignment", help="multiple sequence alignment", required=True) parser.add_argument("-f","--format", default="fasta", help="alignment format [fasta]") parser.add_argument("-g","--gap-cutoff", default=0.5, type=float, help="minimum fraction of non-gap characters per site, else is called unconserved [0.5]") parser.add_argument("-i","--identity", action="store_true", help="report percent identity instead of score") parser.add_argument("-p","--pdb", help="PDB format file", required=True) parser.add_argument("-s","--sequence", help="sequence ID for PDB", required=True) args = parser.parse_args(argv) conservedict = get_alignment_conservation( args.alignment, args.format, args.sequence, args.gap_cutoff, args.identity) if conservedict: # indicating that the sequence was found and something was calculated rewrite_pdb(args.pdb, conservedict, wayout) else: sys.exit("# CANNOT CALCULATE CONSERVATION, EXITING")
def create_parser(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--debug', action='store_true') parser.add_argument('--delimiter') parser.add_argument('--embedding-size', default=200, type=int) parser.add_argument('--graph-path') parser.add_argument('--has-header', action='store_true') parser.add_argument('--input', '-i', dest='infile', required=True) parser.add_argument('--log-level', '-l', type=str.upper, default='INFO') parser.add_argument('--num-walks', default=1, type=int) parser.add_argument('--model', '-m', dest='model_path') parser.add_argument('--output', '-o', dest='outfile', required=True) parser.add_argument('--stats', action='store_true') parser.add_argument('--undirected', action='store_true') parser.add_argument('--walk-length', default=10, type=int) parser.add_argument('--window-size', default=5, type=int) parser.add_argument('--workers', default=multiprocessing.cpu_count(), type=int) return parser
def create_argparser(): parser = argparse.ArgumentParser( parents=[base_parser] + tools.parsers(), add_help=False, formatter_class=argparse.RawDescriptionHelpFormatter, ) group = parser.add_argument_group( 'supported compiler/build-system commands') supported_commands = ', '.join(capture.supported_commands()) group.add_argument( CMD_MARKER, metavar='<cmd>', dest='nullarg', default=None, help=('Command to run the compiler/build-system. ' 'Supported build commands: ' + supported_commands), ) return parser
def main() -> None: parser = argparse.ArgumentParser(description="Smart changelog report", formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("-v", "--version", help="print smartchangelog version number", action="version", version=__version__) parser.add_argument("-r", "--range", help="revision range (in the same meaning than git log command)") parser.add_argument("-g", "--groupby", help="list of criteria", nargs="*") args = parser.parse_args() gitlog = log(revision_range=args.range) changelog = Changelog.parse(gitlog) if args.groupby: criteria = tuple((Commit.property(criterion) for criterion in args.groupby)) else: criteria = () node = changelog.groupby(*criteria) print(node.report()) exit(0)
def getparser(): #Note: Don't want to formally specify these choices, as it limits specification of arbitrary filenames tr_choices = ['first', 'last', 'min', 'max', 'mean', 'med', 'source', '"fn"', '"res"'] te_choices = ['first', 'last', 'intersection', 'union', 'source', '"fn"', '"xmin ymin xmax ymax"'] t_srs_choices = ['first', 'last', '"fn"', '"proj4str"'] #Should read these directly from GDAL r_choices = ['near', 'bilinear', 'cubic', 'cubicspline', 'lanczos', 'average', 'mode'] epilog = fmt_choices('-tr', tr_choices) epilog += fmt_choices('-te', te_choices) epilog += fmt_choices('-t_srs', t_srs_choices) #Note, the formatter_class is a hack to show the choices in the epilog parser = argparse.ArgumentParser(description='Utility to warp stacks of rasters to the same res/extent/proj', \ epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-tr', default='first', help='Output resolution (default: %(default)s)') parser.add_argument('-te', default='intersection', help='Output extent (default: %(default)s)') parser.add_argument('-t_srs', default='first', help='Output projection (default: %(default)s)') parser.add_argument('-dst_ndv', type=float, default=None, help='No data value for output') parser.add_argument('-r', type=str, default='cubic', help='Resampling algorithm (default: %(default)s)', choices=r_choices) parser.add_argument('-outdir', default=None, help='Specify output directory') parser.add_argument('src_fn_list', nargs='+', help='Input filenames (img1.tif img2.tif ...)') return parser
def verify_parser(usage=''): formatter = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(prog='tdda verify', epilog=usage + VERIFY_HELP, formatter_class=formatter) parser.add_argument('-?', '--?', action='help', help='same as -h or --help') parser.add_argument('-a', '--all', action='store_true', help='report all fields, even if there are ' 'no failures') parser.add_argument('-f', '--fields', action='store_true', help='report only fields with failures') parser.add_argument('-c', '--constraints', action='store_true', help='report only individual constraints that fail') parser.add_argument('-1', '--oneperline', action='store_true', help='report each constraint failure on a ' 'separate line') parser.add_argument('-7', '--ascii', action='store_true', help='report without using special characters') parser.add_argument('-type_checking', action='store_true', help='strict or sloppy') parser.add_argument('-epsilon', nargs=1, help='epsilon fuzziness') return parser
def cli(): """Function for cli""" epilog = ('The actions are:\n' '\tnew\t\tCreate a Tornado Application\n' '\trun\t\trun the app and start a Web server for development\n' '\tapi\t\tcreate an API tornado application\n' '\tversion\t\treturns the current version of torn\n') parser = ArgumentParser(prog='torn', description='A full fledged Tornado MVC framework [In-progress]', formatter_class=RawDescriptionHelpFormatter, epilog=epilog, usage='%(prog)s [action [arguments]]') parser.add_argument('action', nargs='*', default=['new', 'api', 'run'], help='Action to be performed with the application') parser.parse_args()
def _main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('input', nargs='?', type=argparse.FileType('rb'), default='-', help="input data ('-' streams from stdin)") parser.add_argument('-i', '--integrate', type=int, default=100, help="Number of blocks to integrate over") setting_keys = ['block_size', 'block_history'] config, args = settings.load_args(parser, setting_keys) blocks = block_reader(args.input, config.block_size, config.block_history) rmss = [] for _, _, block in blocks: rms = np.sqrt(np.sum(block * block.conj)).real rmss.append(rms) if len(rmss) == args.integrate: print(np.mean(rmss)) rmss = []
def _main(): import argparse formatter = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(description=__doc__, formatter_class=formatter) parser.add_argument('toads', nargs='?', type=argparse.FileType('rb'), default='rx.toads', help="toads data (\"-\" streams from stdin)") parser.add_argument('matches', nargs='?', type=argparse.FileType('rb'), default='rx.match', help="toads data (\"-\" streams from stdin)") args = parser.parse_args() toads = toads_data.load_toads(args.toads) detections = toads_data.toads_array(toads, with_ids=True) matches = matchmaker.load_matches(args.matches) reldist(detections, matches, 1, 0)
def _main(): import argparse formatter = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(description=__doc__, formatter_class=formatter) parser.add_argument('tdoa', nargs='?', type=argparse.FileType('r'), default='data.tdoa', help="tdoa data (\"-\" streams from stdin)") parser.add_argument('-o', '--output', dest='output', type=argparse.FileType('w'), default='data.pos', help="output file (\'-\' for stdout)") parser.add_argument('-r', '--rx-coordinates', dest='rx_pos', type=argparse.FileType('r'), default='pos-rx.cfg', help="path to config file that contains the " "coordinates of the receivers") args = parser.parse_args() tdoa_groups = tdoa_est.load_tdoa_groups(args.tdoa) rx_pos = tdoa_est.load_pos_config(args.rx_pos) results = solve(tdoa_groups, rx_pos) save_positions(args.output, results)
def _main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('toad_file', type=str, nargs='*', default="*.toad", help="toad file(s) from receivers [default: *.toad]") parser.add_argument('-o', '--output', type=argparse.FileType('wb'), default='data.toads', help="output file [default: *.taods]") parser.add_argument('-m', '--map', type=argparse.FileType('r'), help="schema for mapping DFT index to transmitter ID " "[default: auto-detect]") args = parser.parse_args() freqmap = load_freqmap(args.map) generate_toads(args.output, args.toad_file, freqmap)
def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('event_file', metavar='event-file', help='the event file') parser.add_argument('tag', help='the image summary tag') parser.add_argument('--prefix', default='image_', help='the image filename prefix (default: %(default)s)') parser.add_argument('--suffix', default='{step:012d}.png', help='the image filename suffix formatting string ' '(default: %(default)s)') args = parser.parse_args() i = 0 for e in tf.train.summary_iterator(args.event_file): if e.HasField('summary'): for v in e.summary.value: if v.HasField('image') and v.tag == args.tag: fname = ('{prefix}' + args.suffix).format( prefix=args.prefix, i=i, step=e.step) with open(fname, 'wb') as f: f.write(v.image.encoded_image_string) i += 1
def top_level_parser(): top_parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='A command-line package manager for Bro.', epilog='Environment Variables:\n\n' ' ``BRO_PKG_CONFIG_FILE``:\t' 'Same as ``--configfile`` option, but has less precedence.' ) top_parser.add_argument('--version', action='version', version='%(prog)s ' + bropkg.__version__) top_parser.add_argument('--configfile', help='Path to Bro Package Manager config file.') top_parser.add_argument('--verbose', '-v', action='count', default=0, help='Increase program output for debugging.' ' Use multiple times for more output (e.g. -vvv).') return top_parser
def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="learn BPE-based word segmentation") parser.add_argument( '--input', '-i', type=argparse.FileType('r'), default=sys.stdin, metavar='PATH', help="Input text (default: standard input).") parser.add_argument( '--output', '-o', type=argparse.FileType('w'), default=sys.stdout, metavar='PATH', help="Output file for BPE codes (default: standard output)") parser.add_argument( '--symbols', '-s', type=int, default=10000, help="Create this many new symbols (each representing a character n-gram) (default: %(default)s))") parser.add_argument( '--min-frequency', type=int, default=2, metavar='FREQ', help='Stop if no symbol pair has frequency >= FREQ (default: %(default)s))') parser.add_argument( '--verbose', '-v', action="store_true", help="verbose mode.") return parser
def main(): parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description='A cmdline tool to enhance PL9K theme for ZSH\n') subparsers = parser.add_subparsers(help='Use {subcommand} -h for each subcommand\'s optional arguments details', dest='command') subparsers.add_parser('init', help='Init the settings in `~/.zshrc` file') subparsers.add_parser('polling', help='Start the polling daemon process') display_parser = subparsers.add_parser('display', help='Print the corresponding info on the terminal') display_parser.add_argument('widget', help='The widget to display, e.g. weather') args = parser.parse_args() if args.command == 'polling': with daemon.DaemonContext(pidfile=daemon.pidfile.PIDLockFile(constants.PID_PATH)): polling() elif args.command == 'display': widgets = sys.modules['thunderbolt100k.widgets'] assert hasattr(widgets, args.widget), 'There is no widget called {0}'.format(args.widget) assert hasattr(getattr(widgets, args.widget), 'display'), 'The widget {0} must contains a `display` method'.format(args.widget) result = getattr(widgets, args.widget).display() if result: print(result) elif args.command == 'init': init_zshrc()
def parse_command(): """Parse the command arguments for generate user config.""" parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=('A command to add swift account, container, and ' 'object disk lists to the Genesis inventory file.')) parser.add_argument('-n', '--nodename', required=True, help=('Name of host in the Genesis inventory YAML' 'file.')) parser.add_argument('-i', '--input-file', required=True, help=('Path to the Genesis inventory YAML file.')) parser.add_argument('-d', '--disklist-file', required=True, help=('Path to the disk list file (flat, non-YAML).')) parser.add_argument('-t', '--disklist-type', required=True, help=('<account | container | object>.')) parser.add_argument('-o', '--output-file', default='output.inventory.yml', help=('Path to the updated Genesis inventory YAML' 'file to be generated.')) return parser