Python argparse.RawDescriptionHelpFormatter() Examples

The following are 40 code examples for showing how to use argparse.RawDescriptionHelpFormatter(). 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module argparse , or try the search function .

Example 1
Project: godot-mono-builds   Author: godotengine   File: cmd_utils.py    License: MIT License 6 votes vote down vote up
def build_arg_parser(description, env_vars={}):
    from argparse import ArgumentParser, RawDescriptionHelpFormatter
    from textwrap import dedent

    base_env_vars = {
        'MONO_SOURCE_ROOT': 'Overrides default value for --mono-sources',
    }

    env_vars_text = '\n'.join(['    %s: %s' % (var, desc) for var, desc in env_vars.items()])
    base_env_vars_text = '\n'.join(['    %s: %s' % (var, desc) for var, desc in base_env_vars.items()])

    epilog=dedent('''\
environment variables:
%s
%s
''' % (env_vars_text, base_env_vars_text))

    return ArgumentParser(
        description=description,
        formatter_class=RawDescriptionHelpFormatter,
        epilog=epilog
    ) 
Example 2
Project: URS   Author: JosephLai241   File: Cli.py    License: MIT License 6 votes vote down vote up
def parse_args(self):
        parser = argparse.ArgumentParser(
            description = self._description,
            epilog = self._epilog, 
            formatter_class = argparse.RawDescriptionHelpFormatter,
            usage = self._usage)

        self._add_flags(parser)
        self._add_export(parser)

        ### Print help message if no arguments are present.
        if len(sys.argv[1:]) == 0:
            parser.print_help()
            raise SystemExit

        args = parser.parse_args()
        return args, parser 
Example 3
Project: jwalk   Author: jwplayer   File: __main__.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 4
Project: single_cell_portal   Author: broadinstitute   File: scp_to_infercnv.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_parser():
    """Set up parsing for command-line arguments
    """
    parser = argparse.ArgumentParser(description=__doc__,  # Use text from file summary up top
                        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--reference-cluster-path',
                    dest='ref_cluster_path',
                    help='Path to SCP cluster file to use as reference ' +
                    '(i.e. normal, control) cells')
    parser.add_argument('--reference-group-name',
                    dest='ref_group_name',
                    help='Name of cell group in SCP cluster file to use as ' +
                    'label for inferCNV references')
    parser.add_argument('--metadata-path',
                    help='Path to SCP metadata file that contains all cells')
    parser.add_argument('--observation-group-name',
                    dest='obs_group_name',
                    help='Name of the cell group in SCP metadata file to ' +
                    'use as label for observations')
    parser.add_argument('--delimiter',
                    help='Delimiter in SCP cluster file',
                    default="\t")
    parser.add_argument('--output-dir',
                    help='Path to write output')
    return parser 
Example 5
Project: JetPack   Author: dsp-jetpack   File: tempest_results_processor.py    License: Apache License 2.0 6 votes vote down vote up
def _create_parser():
    parser = ArgumentParser(description="Compare two tempest xml results",
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument("result_1",
                        help="path to xml result 1")
    parser.add_argument("result_2",
                        help="path to xml result 2")
    '''TODO future functionality
    parser.add_argument("-c", "--csv", dest="output_csv",
                        action="store_true",
                        help="output csv")
    parser.add_argument("-m", "--html", dest="output_html",
                        action="store_true",
                        help="output html")
    parser.add_argument("-n", "--json", dest="output_json",
                        action="store_true",
                        help="output json")
    parser.add_argument("-o", "--output-file", dest="output_file",
                        type=str, required=False,
                        help="If specified, output will be saved to given "
                        "file")
    '''
    return parser 
Example 6
Project: pydarkstar   Author: AdamGagorik   File: base.py    License: MIT License 6 votes vote down vote up
def __init__(self, config='config.yaml', description=None):
        super(BaseOptions, self).__init__()
        logging.debug('BaseOptions.__init__')
        self._ordered_keys = []
        self._exclude_keys = set()

        self._parent = argparse.ArgumentParser(add_help=False)
        self._parser = argparse.ArgumentParser(parents=[self._parent],
                                               description=description,
                                               formatter_class=argparse.RawDescriptionHelpFormatter)

        # config file option
        self.config = config

        # config file
        self._parent.add_argument('--config', type=str, default=self.config, metavar=self.config,
                                  help='configuration file name') 
Example 7
Project: dsub   Author: DataBiosphere   File: provider_base.py    License: Apache License 2.0 6 votes vote down vote up
def create_parser(prog):
  """Create an argument parser, adding in the list of providers."""
  parser = argparse.ArgumentParser(
      prog=prog, formatter_class=argparse.RawDescriptionHelpFormatter)

  parser.add_argument(
      '--provider',
      default='google-v2',
      choices=['local', 'google-v2', 'google-cls-v2', 'test-fails'],
      help="""Job service provider. Valid values are "google-v2" (Google's
        Pipeline API v2alpha1), "google-cls-v2" (Google's Pipelines API v2beta)
        and "local" (local Docker execution).
        "test-*" providers are for testing purposes only.
        (default: google-v2)""",
      metavar='PROVIDER')

  return parser 
Example 8
def _parse_cli_options():
    """
    Parse command line options, returning `parse_args` from `ArgumentParser`.
    """
    parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter,
                            usage="python %(prog)s <options>",
                            epilog="example:\n"
                                   "python %(prog)s -w workflow1 workflow2 -l my_panel_label\n"
                                   "Christophe Antoniewski <drosofff@gmail.com>\n"
                                   "https://github.com/ARTbio/ansible-artimed/tree/master/scritps/galaxykickstart_from_workflow.py")
    parser.add_argument('-w', '--workflow',
                        dest="workflow_files",
                        required=True,
                        nargs='+',
                        help='A space-separated list of galaxy workflow description files in json format', )
    parser.add_argument('-l', '--panel_label',
                        dest='panel_label',
                        default='Tools from workflows',
                        help='The name of the panel where the tools will show up in Galaxy.'
                             'If not specified: "Tools from workflows"')
    return parser.parse_args() 
Example 9
Project: crosentgec   Author: nusnlp   File: apply_bpe.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 10
Project: knmt   Author: fabiencro   File: learn_bpe.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 11
Project: sawtooth-core   Author: hyperledger   File: list_blocks.py    License: Apache License 2.0 6 votes vote down vote up
def add_list_blocks_parser(subparsers, parent_parser):
    """Creates the arg parsers needed for the compare command.
    """
    parser = subparsers.add_parser(
        'list-blocks',
        help='List blocks from different nodes.',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='',
        parents=[parent_parser, base_multinode_parser()])

    parser.add_argument(
        '-n',
        '--count',
        default=10,
        type=int,
        help='the number of blocks to list') 
Example 12
Project: bob   Author: BobBuildTool   File: archive.py    License: GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example 13
Project: safelife   Author: PartnershipOnAI   File: __main__.py    License: Apache License 2.0 6 votes vote down vote up
def run():
    parser = argparse.ArgumentParser(description="""
    The SafeLife command-line tool can be used to interactively play
    a game of SafeLife, print procedurally generated SafeLife boards,
    or convert saved boards to images for easy viewing.

    Please select one of the available commands to run the program.
    You can run `safelife <command> --help` to get more help on a
    particular command.
    """, formatter_class=argparse.RawDescriptionHelpFormatter)
    subparsers = parser.add_subparsers(dest="cmd", help="Top-level command.")
    interactive_game._make_cmd_args(subparsers)
    render_graphics._make_cmd_args(subparsers)
    args = parser.parse_args()
    if args.cmd is None:
        parser.print_help()
    else:
        args.run_cmd(args) 
Example 14
Project: poc   Author: tenable   File: poc_nuuo_upgrade_handle.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    """ Parse command line arguments and start exploit """
    parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.RawDescriptionHelpFormatter,
            epilog="Examples: %(prog)s -t http://192.168.0.1/ -u username -p password -c whoami")

    # Adds arguments to help menu
    parser.add_argument("-h", action="help", help="Print this help message then exit")
    parser.add_argument("-t", dest="target", required="yes", help="Target URL address like: https://localhost:443/")
    parser.add_argument("-u", dest="username", required="yes", help="Username to authenticate")
    parser.add_argument("-p", dest="password", required="yes", help="Password to authenticate")
    parser.add_argument("-c", dest="command", required="yes", help="Shell command to execute")

    # Assigns the arguments to various variables
    args = parser.parse_args()

    run(args.target, args.username, args.password, args.command)


#
# Main
# 
Example 15
Project: minikerberos   Author: skelsec   File: getTGT.py    License: MIT License 6 votes vote down vote up
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Polls the kerberos service for a TGT for the sepcified user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_url', help='the kerberos target string. ')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logging.basicConfig(level=logging.INFO)
	elif args.verbose == 1:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig(level=1)
	
	asyncio.run(amain(args)) 
Example 16
Project: minikerberos   Author: skelsec   File: getS4U2proxy.py    License: MIT License 6 votes vote down vote up
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Gets an S4U2proxy ticket impersonating given user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_url', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')
	parser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server "fileserver". IMPORTANT: SERVER\'S HOSTNAME MUST BE USED, NOT IP!!!')
	parser.add_argument('targetuser', help='')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logger.setLevel(logging.WARNING)
	elif args.verbose == 1:
		logger.setLevel(logging.INFO)
	else:
		logger.setLevel(1)

	asyncio.run(amain(args)) 
Example 17
Project: minikerberos   Author: skelsec   File: getTGS.py    License: MIT License 6 votes vote down vote up
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Polls the kerberos service for a TGS for the sepcified user and specified service', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_string', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')
	parser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server "fileserver". IMPORTANT: SERVER\'S HOSTNAME MUST BE USED, NOT IP!!!')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-u', action='store_true', help='Use UDP instead of TCP (not tested)')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logging.basicConfig(level=logging.INFO)
	elif args.verbose == 1:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig(level=1)
	
	asyncio.run(amain(args)) 
Example 18
Project: ccat   Author: cisco-config-analysis-tool   File: args.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getfilenames():
    global args
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
                                     description="Cisco Configuration Analysis Tool",
                                     epilog='Usage example:\n  ccat  smth/config_folder -vlanmap smth/vlanmap_file')
    parser.add_argument("configs", type=str, nargs='?', default=0, help="full path to the configuration file or folder with config(s)")
    parser.add_argument("-vlanmap", type=str, help="path to vlanmap (file that determine how critical is certain vlan, you can find example in 'example' folder)")
    parser.add_argument("-output", type=str, help="path to output html files directory")
    parser.add_argument("--no-console-display", action='store_true', help="to output analysis results in html files directory or into network graph")
    parser.add_argument("--no-ipv6", action='store_true', help="if you're not using IPv6")
    parser.add_argument("--disabled-interfaces", action='store_true', help="check interfaces even if they are turned off")
    parser.add_argument("--storm_level", type=float, help="to set up appropriate level for storm-control (by default value=80)")
    parser.add_argument("--max_number_mac", type=int, help="to set up maximum number of mac-addresses for port-security (by default value=10)")
    parser.add_argument("--dump-creds", action='store_true', help="enable credentials harvesting")
    parser.add_argument("--debug", action='store_true', help="enable debug output")
    graph_group = parser.add_argument_group('Network graph')
    graph_group.add_argument("--graph", type=str, nargs='?', default=0, help="left the argument empty to get into interactive mode or define a file name for graph output in png extension")
    args = parser.parse_args()
    if not(args.configs):
        print ('Usage example:\n  ccat  smth/config_folder -vlanmap smth/vlanmap_file\n\nFor more details try --help')
        exit()
    if args.no_console_display and not args.output and args.graph == 0:
        print('\nYou should define html files directory with -output key OR use --graph key to use this options\n\nFor more details try --help')
        exit()
    return _getargs___arg_parser(args.configs, args.vlanmap) 
Example 19
Project: SOQAL   Author: husseinmozannar   File: extractPage.py    License: MIT License 6 votes vote down vote up
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) 
Example 20
Project: pycozmo   Author: zayfod   File: pycozmo_anim.py    License: MIT License 6 votes vote down vote up
def parse_arguments():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    subparsers = parser.add_subparsers(dest="cmd", required=True)

    subparser = subparsers.add_parser("info", help="view clips and keyframes in an animation file")
    subparser.add_argument("input", help="input file specification")

    subparser = subparsers.add_parser(
        "json", help="convert an animation in FlatBuffers format to JSON format")
    subparser.add_argument("input", help="input file specification")
    subparser.add_argument("-o", "--output", help="output file specification")

    subparser = subparsers.add_parser(
        "bin", help="convert an animation in JSON format to FlatBuffers format.")
    subparser.add_argument("input", help="input file specification")
    subparser.add_argument("-o", "--output", help="output file specification")

    subparser = subparsers.add_parser("images", help="export procedural face images from an animation file")
    subparser.add_argument("input", help="input file specification")
    subparser.add_argument("-p", "--prefix", help="output file specification prefix")

    args = parser.parse_args()
    return args 
Example 21
Project: monasca-analytics   Author: openstack   File: run.py    License: Apache License 2.0 6 votes vote down vote up
def setup_parser():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=textwrap.dedent(__doc__.strip()),
        add_help=False)

    parser.add_argument('-c', '--config',
                        help='Config file.', required=True)
    # "-d" currently unused
    parser.add_argument('-d', '--debug',
                        help='Show debug messages.', action='store_true')
    parser.add_argument('-h', '--help',
                        help='Show this screen.', action='help')
    parser.add_argument('-l', '--log_config',
                        help='Log config file\'s path.', required=True)
    parser.add_argument('-p', '--spark_path',
                        help='Spark\'s path.', required=True)
    parser.add_argument('-s', '--sources',
                        help='A list of data sources.', nargs='*')
    parser.add_argument('-v', '--version',
                        help='Show version.', action='version',
                        version=setup_property.VERSION)

    return parser 
Example 22
Project: recipes-py   Author: luci   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def parse_and_run():
  """Parses the command line and runs the chosen subcommand.

  Returns the command's return value (either int or None, suitable as input to
  `os._exit`).
  """
  parser = argparse.ArgumentParser(
      description='Interact with the recipe system.')

  _add_common_args(parser)

  subp = parser.add_subparsers(dest='command')
  for module in _COMMANDS:
    description = module.__doc__
    helplines = []
    for line in description.splitlines():
      line = line.strip()
      if not line:
        break
      helplines.append(line)
    module.add_arguments(subp.add_parser(
        module.__name__.split('.')[-1],  # use module's short name
        formatter_class=argparse.RawDescriptionHelpFormatter,
        help=' '.join(helplines),
        description=description,
    ))

  args = parser.parse_args()
  _common_post_process(args)
  args.postprocess_func(parser.error, args)

  return args.func(args) 
Example 23
Project: gftools   Author: googlefonts   File: gftools-fix-vf-meta.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=__doc__
    )
    parser.add_argument("fonts", nargs="+", help=(
            "Paths to font files. Fonts must be part of the same family."
        )
    )
    args = parser.parse_args()
    fonts = args.fonts

    # This monstrosity exists so we don't break the v1 api.
    italic_font = None
    if len(fonts) > 2:
        raise Exception(
            "Can only add STAT tables to a max of two fonts. "
            "Run gftools fix-vf-meta --help for usage instructions"
        )
    elif len(fonts) == 2:
        if "Italic" in fonts[0]:
            italic_font = TTFont(fonts[0])
            roman_font = TTFont(fonts[1])
        elif "Italic" in fonts[1]:
            italic_font = TTFont(fonts[1])
            roman_font = TTFont(fonts[0])
        else:
            raise Exception("No Italic font found!")
    else:
        roman_font = TTFont(fonts[0])
    update_nametable(roman_font)
    if italic_font:
        update_nametable(italic_font)
    build_stat(roman_font, italic_font)
    roman_font.save(roman_font.reader.file.name + ".fix")
    if italic_font:
        italic_font.save(italic_font.reader.file.name + ".fix") 
Example 24
Project: single_cell_portal   Author: broadinstitute   File: SortSparseMatrix.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __main__(argv):
    """Command Line parser for sort_sparse_matrix
    Inputs-
    command line arguments
    """
    # create the argument parser
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    # add arguments
    parser.add_argument('matrix_file', help='Sparse Matrix file')
    parser.add_argument('--sorted_matrix_file', '-o', help='Gene sorted sparse matrix file path', default=None)
    # call sort_sparse_matrix with parsed args
    args = parser.parse_args()
    sort_sparse_matrix(matrix_file=args.matrix_file, sorted_matrix_file=args.sorted_matrix_file)

# python default 
Example 25
def create_parser():
    """Set up parsing for command-line arguments
    """
    parser = ArgumentParser(description=__doc__,  # Use text from file summary up top
                        formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('--matrix-path',
                    help='Path to expression matrix file')
    parser.add_argument('--matrix-delimiter',
                    help='Delimiter in expression matrix',
                    default='\t')
    parser.add_argument('--gen-pos-file',
                    help='Path to gen_pos.txt genomic positions file from inferCNV')
    parser.add_argument('--cluster-names',
                    help='Names of cluster groups',
                    nargs='+')
    parser.add_argument('--reference-group-name',
                    dest='ref_group_name',
                    help='Name of cell group in SCP cluster file to use as ' +
                    'label for inferCNV references')
    parser.add_argument('--ref-cluster-names',
                    help='Names of reference (normal) cluster groups',
                    nargs='+', default=[])
    parser.add_argument('--ordered-labels',
                    help='Sorted labels for clusters',
                    nargs='+', default=[])
    parser.add_argument('--heatmap-thresholds-path',
                    help='Path to heatmap thresholds file', required=False)
    # parser.add_argument('--ref-heatmap-thresholds',
    #                 help='Numeric thresholds for heatmap of reference (normal) cluster groups',
    #                 nargs='+', required=False)
    parser.add_argument('--cluster-paths',
                    help='Path or URL to cluster group files',
                    nargs='+')
    parser.add_argument('--metadata-path',
                    help='Path or URL to metadata file')
    parser.add_argument('--output-dir',
                    help='Path to write output')

    return parser 
Example 26
Project: GelReportModels   Author: genomicsengland   File: avdlDoxyFilter.py    License: Apache License 2.0 5 votes vote down vote up
def parse_args(args):
    """
    Takes in the command-line arguments list (args), and returns a nice argparse
    result with fields for all the options.
    Borrows heavily from the argparse documentation examples:
    <http://docs.python.org/library/argparse.html>
    """

    # The command line arguments start with the program name, which we don't
    # want to treat as an argument for argparse. So we remove it.
    args = args[1:]

    # Construct the parser (which is stored in parser)
    # Module docstring lives in __doc__
    # See http://python-forum.com/pythonforum/viewtopic.php?f=3&t=36847
    # And a formatter class so our examples in the docstring look good. Isn't it
    # convenient how we already wrapped it to 80 characters?
    # See http://docs.python.org/library/argparse.html#formatter-class
    parser = argparse.ArgumentParser(description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    # Now add all the options to it
    parser.add_argument("avdl", type=argparse.FileType('r'),
        help="the AVDL file to read")

    return parser.parse_args(args) 
Example 27
Project: video-caption-openNMT.pytorch   Author: xiadingZ   File: apply_bpe.py    License: MIT License 5 votes vote down vote up
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'))")
    parser.add_argument(
        '--vocabulary', type=argparse.FileType('r'), default=None,
        metavar="PATH",
        help="Vocabulary file (built with get_vocab.py). If provided, this script reverts any merge operations that produce an OOV.")
    parser.add_argument(
        '--vocabulary-threshold', type=int, default=None,
        metavar="INT",
        help="Vocabulary threshold. If vocabulary is provided, any word with frequency < threshold will be treated as OOV")
    parser.add_argument(
        '--glossaries', type=str, nargs='+', default=None,
        metavar="STR",
        help="Glossaries. The strings provided in glossaries will not be affected"+
             "by the BPE (i.e. they will neither be broken into subwords, nor concatenated with other subwords")

    return parser 
Example 28
Project: video-caption-openNMT.pytorch   Author: xiadingZ   File: learn_bpe.py    License: MIT License 5 votes vote down vote up
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('--dict-input', action="store_true",
        help="If set, input file is interpreted as a dictionary where each line contains a word-count pair")
    parser.add_argument(
        '--verbose', '-v', action="store_true",
        help="verbose mode.")

    return parser 
Example 29
Project: pydarkstar   Author: AdamGagorik   File: makebin.py    License: MIT License 5 votes vote down vote up
def __init__(self):
        self.work = os.getcwd()
        self.python = shutil.which('python3')
        self.project_path = os.path.join(os.path.dirname(os.path.abspath(__file__)))
        self.package_name = 'pydarkstar'
        self.package_path = os.path.join(self.project_path, self.package_name)
        self.apps_path = os.path.join(self.package_path, 'apps')
        self.bin_path = os.path.join(self.project_path, 'bin')
        self.apps_list = {
            'broker': 'pydarkstar.apps.broker.run',
            'seller': 'pydarkstar.apps.seller.run',
            'buyer': 'pydarkstar.apps.buyer.run',
            'refill': 'pydarkstar.apps.refill.run',
            'clear': 'pydarkstar.apps.clear.run',
            'scrub': 'pydarkstar.apps.scrub.run',
            'alter': 'pydarkstar.apps.alter.run',
        }

        if self.python is None:
            self.python = 'python'

        log_parameter('work', self.work)
        log_parameter('project_path', self.project_path)
        log_parameter('package_name', self.package_name)
        log_parameter('package_path', self.package_path)
        log_parameter('python', self.python)
        log_parameter('bin_path', self.bin_path)

        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.parse_args()

        try:
            assert os.path.exists(self.work)
            assert os.path.exists(self.project_path)
            assert os.path.exists(self.package_path)
            assert os.path.exists(self.apps_path)
        except AssertionError:
            logging.exception('invalid configuration')
            exit(-1) 
Example 30
def _parse_cli_options():
    """
    Parse command line options, returning `parse_args` from `ArgumentParser`.
    """
    parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter,
                            usage="python %(prog)s <options>",
                            epilog="Workflow files must have been exported from Galaxy release 16.04 or newer.\n\n"
                                   "example:\n"
                                   "python %(prog)s -w workflow1 workflow2 -o mytool_list.yml -l my_panel_label\n"
                                   "Christophe Antoniewski <drosofff@gmail.com>\n"
                                   "https://github.com/ARTbio/ansible-artimed/tree/master/extra-files/generate_tool_list_from_ga_workflow_files.py")
    parser.add_argument('-w', '--workflow',
                        dest="workflow_files",
                        required=True,
                        nargs='+',
                        help='A space separated list of galaxy workflow description files in json format', )
    parser.add_argument('-o', '--output-file',
                        required=True,
                        dest='output_file',
                        help='The output file with a yml tool list')
    parser.add_argument('-l', '--panel_label',
                        dest='panel_label',
                        default='Tools from workflows',
                        help='The name of the panel where the tools will show up in Galaxy.'
                             'If not specified: "Tools from workflows"')
    return parser.parse_args() 
Example 31
Project: fac   Author: mickael9   File: __init__.py    License: MIT License 5 votes vote down vote up
def create_parser(self, subparser, parents):
        doc = self.__doc__ or ""
        description = textwrap.dedent(doc.strip("\n") or self.help)
        epilog = textwrap.dedent(self.epilog.strip("\n"))
        help = self.help or (description and description.splitlines()[0])

        command_parser = argparse.ArgumentParser(add_help=False)
        group = command_parser.add_argument_group("%s options" % self.name)
        for args, kwargs in self.arguments:
            group.add_argument(*args, **kwargs)

        subcommands_parser = argparse.ArgumentParser(
            add_help=False,
            usage="%(prog)s " + self.name
        )

        if self.subcommands:
            subcommand_parser = subcommands_parser.add_subparsers(
                metavar='SUBCOMMAND',
                title=None,
            )
            for subcommand_class in self.subcommands:
                subcommand = subcommand_class(self.manager)
                subcommand.create_parser(subcommand_parser,
                                         [command_parser] + parents)

        self.parser = subparser.add_parser(
            self.name,
            usage=self.usage,
            help=help,
            description=description,
            epilog=epilog,
            parents=[subcommands_parser, command_parser] + parents,
            add_help=False,
            formatter_class=argparse.RawDescriptionHelpFormatter,
        )

        self.parser.set_defaults(run=self.run) 
Example 32
Project: mysql_utils   Author: pinterest   File: mysql_grants.py    License: GNU General Public License v2.0 5 votes vote down vote up
def main():
    action_desc = """Action description:

stdout - dump grants to stdout
check - check grants on the instance and ouput errors to stdout
import - import grants on to the instance and then check
nuke_then_import - DANGEROUS! Delete all grants, reimport and then recheck

Note: Grants do *NOT* run through replication. If you need to make a change,
you will need to run it against the entire replica set.
"""

    parser = argparse.ArgumentParser(description='MySQL grant manager',
                                     epilog=action_desc,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-i',
                        '--instance',
                        help='Instance to act on if other than localhost:3306',
                        default=''.join((host_utils.HOSTNAME, ':3306')))
    parser.add_argument('-a',
                        '--action',
                        choices=('stdout',
                                 'check',
                                 'import',
                                 'nuke_then_import'),
                        required=True)

    args = parser.parse_args()
    instance = host_utils.HostAddr(args.instance)

    if args.action == 'stdout':
        grants = mysql_lib.get_all_mysql_grants()
        for grant in grants.iteritems():
            print format_grant(grant[1])
    else:
        problems = manage_mysql_grants(instance, args.action)
        if len(problems) > 0:
            print "Current problems:"
            print '\n'.join(problems)
            sys.exit(1) 
Example 33
Project: knmt   Author: fabiencro   File: apply_bpe.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 34
Project: westpa   Author: westpa   File: core.py    License: MIT License 5 votes vote down vote up
def make_parser(self, prog=None, usage=None, description=None, epilog=None, args=None):
        prog = prog or self.prog
        usage = usage or self.usage
        description = description or self.description
        epilog = epilog or self.epilog
        parser = argparse.ArgumentParser(prog=prog, usage=usage, description=description, epilog=epilog,
                                         formatter_class=argparse.RawDescriptionHelpFormatter,
                                         conflict_handler='resolve')
        self.add_all_args(parser)
        return parser 
Example 35
Project: westpa   Author: westpa   File: core.py    License: MIT License 5 votes vote down vote up
def add_to_subparsers(self, subparsers):
        subparser = subparsers.add_parser(self.subcommand, help=self.help_text, description=self.description,
                                          formatter_class=argparse.RawDescriptionHelpFormatter,
                                          )
        self.add_all_args(subparser)
        subparser.set_defaults(west_subcommand=self)
        self.subparser = subparser 
Example 36
Project: AI-Robot-Challenge-Lab   Author: microsoft   File: bot-move-grippers.py    License: MIT License 5 votes vote down vote up
def main():
    """RSDK Gripper Example: send a command to control the grippers.

    Run this example to command various gripper movements while
    adjusting gripper parameters, including calibration, and velocity:
    Uses the intera_interface.Gripper class and the
    helper function, intera_external_devices.getch.
    """
    epilog = """
See help inside the example with the '?' key for key bindings.
    """
    rp = intera_interface.RobotParams()
    valid_limbs = rp.get_limb_names()
    if not valid_limbs:
        rp.log_message(("Cannot detect any limb parameters on this robot. "
                        "Exiting."), "ERROR")
        return
    limb = valid_limbs[0]
    print("Using limb: {}.".format(limb))
    arg_fmt = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=arg_fmt,
                                     description=main.__doc__,
                                     epilog=epilog)
    parser.add_argument(
        "-a", "--action", dest="action", default="open",
        choices=["open", "close"],
        help="Action to perform with the gripper. Options: close or open"
    )
    args = parser.parse_args(rospy.myargv()[1:])

    print("Initializing node... ")
    rospy.init_node("sdk_gripper_keyboard")

    move_gripper(limb, args.action) 
Example 37
Project: sawtooth-core   Author: hyperledger   File: transaction.py    License: Apache License 2.0 5 votes vote down vote up
def add_transaction_parser(subparsers, parent_parser):
    """Adds argument parsers for the transaction list and show commands

        Args:
            subparsers: Add parsers to this subparser object
            parent_parser: The parent argparse.ArgumentParser object
    """
    parser = subparsers.add_parser(
        'transaction',
        help='Shows information on transactions in the current chain',
        description='Provides subcommands to display information about '
        'the transactions in the current blockchain.')

    grand_parsers = parser.add_subparsers(
        title='subcommands',
        dest='subcommand')

    grand_parsers.required = True

    grand_parsers.add_parser(
        'list',
        description='Lists all transactions in the current blockchain.',
        parents=[base_http_parser(), base_list_parser()],
        formatter_class=argparse.RawDescriptionHelpFormatter)

    show_parser = grand_parsers.add_parser(
        'show',
        description='Displays information for the specified transaction.',
        parents=[base_http_parser(), base_show_parser()],
        formatter_class=argparse.RawDescriptionHelpFormatter)

    show_parser.add_argument(
        'transaction_id',
        type=str,
        help='id (header_signature) of the transaction') 
Example 38
Project: sawtooth-core   Author: hyperledger   File: batch.py    License: Apache License 2.0 5 votes vote down vote up
def add_batch_list_parser(subparsers, parent_parser):
    description = (
        'Displays all information about all committed Batches for '
        'the specified validator, including the Batch id, public keys of all '
        'signers, and number of transactions in each Batch.')

    subparsers.add_parser(
        'list',
        description=description,
        parents=[base_http_parser(), base_list_parser()],
        formatter_class=argparse.RawDescriptionHelpFormatter) 
Example 39
Project: paper-to-git   Author: maxking   File: paper_git.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    """The `paper_git command dispatcher."""
    parser = argparse.ArgumentParser(
        description="""\
        The Paper-to-Git system
        Copyright 2017 Abhilash Raj""",
        formatter_class=argparse.RawDescriptionHelpFormatter)

    subparser = parser.add_subparsers(title='Commands')
    subcommands = []
    for command_class in find_components('papergit.commands', BaseCommand):
        command = command_class()
        assert issubclass(command_class, BaseCommand)
        subcommands.append(command)
    for command in subcommands:
        command_parser = subparser.add_parser(
            command.name, help=command.__doc__)
        command.add(parser, command_parser)
        command_parser.set_defaults(func=command.process)

    args = parser.parse_args()

    if len(args.__dict__) < 1:
        # No arguments or subcommands were given.
        parser.print_help()
        parser.exit()
    # Initialize the system.
    initialize()
    # Run the given command.
    args.func(args) 
Example 40
Project: bob   Author: BobBuildTool   File: jenkins.py    License: GNU General Public License v3.0 5 votes vote down vote up
def doJenkins(argv, bobRoot):
    subHelp = "\n             ... ".join(sorted(
        [ "{} {}".format(c, d[1]) for (c, d) in availableJenkinsCmds.items() ]))
    parser = argparse.ArgumentParser(prog="bob jenkins",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="""Configure jenkins. The following subcommands are available:

  bob jenkins {}
""".format(subHelp))
    parser.add_argument('subcommand', help="Subcommand")
    parser.add_argument('args', nargs=argparse.REMAINDER,
                        help="Arguments for subcommand")
    parser.add_argument('-c', dest="configFile", default=[], action='append', metavar="NAME",
        help="Use additional config File.")

    args = parser.parse_args(argv)

    recipes = RecipeSet()
    recipes.defineHook('jenkinsNameFormatter', jenkinsNameFormatter)
    recipes.setConfigFiles(args.configFile)
    recipes.parse()

    if args.subcommand in availableJenkinsCmds:
        BobState().setAsynchronous()
        try:
            availableJenkinsCmds[args.subcommand][0](recipes, args.args)
        except urllib.error.HTTPError as e:
            raise BuildError("HTTP error: " + str(e))
        except OSError as e:
            raise BuildError("OS error: " + str(e))
        finally:
            BobState().setSynchronous()
    else:
        parser.error("Unknown subcommand '{}'".format(args.subcommand))