Пример #1
0
def create_parser(formatter_class=None):
    ''' Create lkadmin CLI argument parser '''

    if not formatter_class:
        formatter_class = CustomArgparseFormatter

    parser = ArgumentParser(description='Administer a Laniakea instance', formatter_class=formatter_class)
    subparsers = parser.add_subparsers(dest='sp_name', title='subcommands')

    # generic arguments
    parser.add_argument('--verbose', action='store_true', dest='verbose',
                        help='Enable debug messages.')
    parser.add_argument('--version', action='store_true', dest='show_version',
                        help='Display the version of Laniakea itself.')

    import lkadmin.core as core
    core.add_cli_parser(subparsers)

    import lkadmin.synchrotron as synchrotron
    synchrotron.add_cli_parser(subparsers)

    import lkadmin.spears as spears
    spears.add_cli_parser(subparsers)

    import lkadmin.ariadne as ariadne
    ariadne.add_cli_parser(subparsers)

    import lkadmin.isotope as isotope
    isotope.add_cli_parser(subparsers)

    import lkadmin.planter as planter
    planter.add_cli_parser(subparsers)

    return parser
Пример #2
0
def make_parser(prog):
    parser = ArgumentParser(prog)
    parser.add_argument('--version', action='version', version='%(prog)s ' + VERSION)

    command_parsers = parser.add_subparsers(metavar='command', dest='command')
    command_parsers.required = True

    command_search_parser = command_parsers.add_parser('search', help='search for items')
    command_search_parser.add_argument('type', help='type of item to search for',
                                       choices=['movie', 'person', 'character', 'company', 'keyword'])
    command_search_parser.add_argument('key', help='title or name of item to search for')
    command_search_parser.add_argument('-n', type=int, help='number of items to list')
    command_search_parser.add_argument('--first', action='store_true', help='display only the first result')
    command_search_parser.set_defaults(func=search_item)

    command_get_parser = command_parsers.add_parser('get', help='retrieve information about an item')
    command_get_parser.add_argument('type', help='type of item to retrieve',
                                    choices=['movie', 'person', 'character', 'company', 'keyword'])
    command_get_parser.add_argument('key', help='IMDb id (or keyword name) of item to retrieve')
    command_get_parser.add_argument('-n', type=int, help='number of movies to list (only for keywords)')
    command_get_parser.set_defaults(func=get_item)

    command_top_parser = command_parsers.add_parser('top', help='get top ranked movies')
    command_top_parser.add_argument('-n', type=int, help='number of movies to list')
    command_top_parser.add_argument('--first', action='store_true', help='display only the first result')
    command_top_parser.set_defaults(func=get_top_movies)

    command_bottom_parser = command_parsers.add_parser('bottom', help='get bottom ranked movies')
    command_bottom_parser.add_argument('-n', type=int, help='number of movies to list')
    command_bottom_parser.add_argument('--first', action='store_true', help='display only the first result')
    command_bottom_parser.set_defaults(func=get_bottom_movies)

    return parser
 def run(cls):
     parser = ArgumentParser(
         description=("The theme development utility. "
                      "Includes three modes: "
                      "one for serving a theme compiled on-the-fly, "
                      "the other for compiling statically a theme "
                      "and the latter to dump URLs to files")
     )
     subparsers = parser.add_subparsers(
         title="Commands",
         description="Available commands (modes of operation)"
     )
     for key, target in cls.commands.items():
         if target is None:
             target = cls
         else:
             target = getattr(cls, target)
         subparser = subparsers.add_parser(
             key,
             description=target.__doc__,
             help=target.__doc__.splitlines()[0]
         )
         target.setup_parser(subparser)
         subparser.set_defaults(target=target)
     args = parser.parse_args()
     if hasattr(args, 'target'):
         sys.exit(args.target.main(args))
     else:
         parser.print_usage()
         sys.exit(-1)
Пример #4
0
def main():
    """
    Main entry point for CLI
    
    """
    load_maestro_rc()
    parser = ArgumentParser(prog='maestro', description='DevOps management')
    sub = parser.add_subparsers()
    sub_tasks = sub.add_parser('tasks', help='Tasks')
    sub_tasks.add_argument('-l', '--list', action='store_true', dest='tasks_list', default=False, \
        help='Show available tasks')
    sub_tasks.add_argument('-r', '--run', action='store', dest='tasks_task', \
        help='Task to run')
    sub_tasks.set_defaults(func=parse_tasks)
    
    sub_nodes = sub.add_parser('nodes', help='Nodes')
    sub_nodes.add_argument('-c', '--cloud-provider', action='store', dest='cloud_provider', \
        choices=config.AVAILABLE_CLOUD_PROVIDERS, default=None, required=True, \
        help='Name of cloud provider to use')
    sub_nodes.add_argument('-l', '--list', action='store_true', dest='list', default=False, \
        help='List all nodes')
    sub_nodes.add_argument('-t', '--task', action='store', dest='task', \
        help='Task to run on nodes')
    sub_nodes.add_argument('-u', '--user', action='store', dest='user', \
        help='Username to use when running task')
    sub_nodes.add_argument('-p', '--parallel', action='store_true', default=False, \
        help='Run task in parallel among nodes')
    sub_nodes.set_defaults(func=parse_nodes)
        
    args = parser.parse_args()
    args.func(args)
    # disconnect
    disconnect_all()
    sys.exit(0)
Пример #5
0
    def test_repl_subcommand(self):
        p = ArgumentParser()
        p.add_argument("--foo")
        p.add_argument("--bar")

        s = p.add_subparsers()
        s.add_parser("list")
        s.add_parser("set")
        show = s.add_parser("show")

        def abc():
            pass

        show.add_argument("--test")
        ss = show.add_subparsers()
        de = ss.add_parser("depth")
        de.set_defaults(func=abc)

        c = CompletionFinder(p, always_complete_options=True)

        expected_outputs = (
            ("prog ", ["-h", "--help", "--foo", "--bar", "list", "show", "set"]),
            ("prog li", ["list "]),
            ("prog s", ["show", "set"]),
            ("prog show ", ["--test", "depth", "-h", "--help"]),
            ("prog show d", ["depth "]),
            ("prog show depth ", ["-h", "--help"]),
        )

        for cmd, output in expected_outputs:
            self.assertEqual(set(self.run_completer(p, c, cmd)), set(output))
Пример #6
0
def arg_parser():
    parser = ArgumentParser()
    subparsers = parser.add_subparsers(help='Commands', dest='command')

    repmatch_parser = subparsers.add_parser('repmatch', help='compare two replicate samples')
    repmatch_parser.add_argument('vcf1', help='Sample 1 VCF/BCF input (- for stdin)')
    repmatch_parser.add_argument('vcf2', help='Sample 2 VCF/BCF input (- for stdin)')
    repmatch_parser.add_argument('--out1', help='Sample 1 VCF/BCF output (optional)')
    repmatch_parser.add_argument('--out2', help='Sample 2 VCF/BCF output (optional)')
    repmatch_parser.add_argument('--name1', metavar='N', default=0, type=tryint,
                                 help='Name or index of sample in sample 1 file (default=0)')
    repmatch_parser.add_argument('--name2', metavar='N', default=0, type=tryint,
                                 help='Name or index of sample in sample 2 file (default=0)')

    add_common_args(repmatch_parser)

    dbmatch_parser = subparsers.add_parser('dbmatch', help='compare a database of alleles to a sample')
    dbmatch_parser.add_argument('database', help='Database of alleles VCF/BCF input (- for stdin)')
    dbmatch_parser.add_argument('sample',   help='Sample VCF/BCF input (- for stdin)')
    dbmatch_parser.add_argument('--name', metavar='N', default=0, type=tryint,
                                 help='Name or index of sample in sample file (default=0)')
    dbmatch_parser.add_argument('-o', '--output', default='-', help='Sample VCF/BCF output')

    add_common_args(dbmatch_parser)

    parser.add_argument('--debug', action='store_true', help='Output extremely verbose debugging information')
    parser.add_argument('--profile', action='store_true', help='Profile code performance')

    return parser
Пример #7
0
def main(args=None):
    from argparse import ArgumentParser
    from pathlib import Path
    from sys import argv

    parser = ArgumentParser(description="Find peaks in an nD image")
    subparsers = parser.add_subparsers()

    find_parser = subparsers.add_parser("find")
    find_parser.add_argument("image", type=Path, help="The image to process")
    find_parser.add_argument("--size", type=int, nargs=2, default=(1, 1),
                             help="The range of sizes (in px) to search.")
    find_parser.add_argument("--threshold", type=float, default=5,
                             help="The minimum spot intensity")
    find_parser.add_argument("--format", choices={"csv", "txt", "pickle"}, default="csv",
                             help="The output format (for stdout)")
    find_parser.add_argument("--edge", type=int, default=0,
                             help="Minimum distance to edge allowed.")
    find_parser.set_defaults(func=find)

    plot_parser = subparsers.add_parser("plot")
    plot_parser.add_argument("image", type=Path, help="The image to process")
    plot_parser.add_argument("peaks", type=Path, help="The peaks to plot")
    plot_parser.add_argument("outfile", nargs='?', type=Path, default=None,
                             help="Where to save the plot (omit to display)")
    plot_parser.add_argument("--axes", type=int, nargs=2, default=(0, 1),
                             help="The axes to plot")
    plot_parser.set_defaults(func=plot)

    for p in (plot_parser, find_parser):
        p.add_argument("--scale", nargs="*", type=float,
                       help="The scale for the points along each axis.")

    args = parser.parse_args(argv[1:] if args is None else args)
    args.func(args)
Пример #8
0
def parse_args():
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("conf_file", help=u"configuration to use")
    parser.add_argument(
        "-b", "--badge", default=u"invited", help=u"badge" u" (title or id) which is used to mark invited users"
    )
    parser.add_argument("-i", "--instance", default=None)
    subparsers = parser.add_subparsers()

    invite_parser = subparsers.add_parser("invite", help=u"invite new users" u" to adhocracy")
    invite_parser.add_argument("csv_file", help=u"csv files of users to add")
    invite_parser.add_argument("template", help=u"text file with mail body")
    invite_parser.add_argument("-s", "--subject", default=u"Welcome to Adhocracy!", help=u"email subject")
    invite_parser.set_defaults(action=u"invite")

    reinvite_parser = subparsers.add_parser(
        "reinvite", help=u"invite again all users who have not yet activated" u" their accounts"
    )
    reinvite_parser.add_argument("template", help=u"text file with mail body")
    reinvite_parser.add_argument("-s", "--subject", default=u"Welcome to Adhocracy!", help=u"email subject")
    reinvite_parser.set_defaults(action=u"reinvite")

    revoke_parser = subparsers.add_parser(
        "revoke", help=u"revoke invitation for all users who have not" u" activated their accounts after invitation"
    )
    revoke_parser.set_defaults(action=u"revoke")

    uninvite_parser = subparsers.add_parser("uninvite", help=u'remove "invited"-badge from given users')
    uninvite_parser.add_argument("users", metavar="user", nargs="+")
    uninvite_parser.add_argument(
        "-r", "--revoke", action="store_true", help=u"also revoke invitation" u" if not already activated"
    )
    uninvite_parser.set_defaults(action=u"uninvite")

    return parser.parse_args()
def _get_args():
    parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter, description=PROG_DESCRIPTION)
    subparsers = parser.add_subparsers(dest="mode")

    parser_getgfid = subparsers.add_parser("gfid")
    parser_getgfid.add_argument("path", help="Path")

    parser_getxtime = subparsers.add_parser("xtime")
    parser_getxtime.add_argument("path", help="Path")
    parser_getxtime.add_argument("master_uuid", help="Master UUID")

    parser_getstime = subparsers.add_parser("stime")
    parser_getstime.add_argument("path", help="Path")
    parser_getstime.add_argument("master_uuid", help="Master UUID")
    parser_getstime.add_argument("slave_uuid", help="Master UUID")

    parser_archivelist = subparsers.add_parser("listfromtar")
    parser_archivelist.add_argument("path", help="Path of Archive(Tar file)")

    parser_volmark_master = subparsers.add_parser("volmarkmaster")
    parser_volmark_master.add_argument("path", help="Path")

    parser_volmark_slave = subparsers.add_parser("volmarkslave")
    parser_volmark_slave.add_argument("path", help="Path")

    return parser.parse_args()
Пример #10
0
def define_arguments():
    ap = ArgumentParser()
    sp = ap.add_subparsers(title="Subcommands", dest="subcommand")
    sp.required = True

    #=====
    grpscmd = sp.add_parser("groupdefs",
                            description=groupdefs.__doc__)
    grpscmd.add_argument("profile", help="AWS profile (from ~/.aws/config)")
    grpscmd.add_argument("region", help="AWS region")
    grpscmd.add_argument("vpc", help="VPC ID or 'classic'")
    grpscmd.set_defaults(do=groupdefs)

    std_args = ArgumentParser(add_help=False)
    std_args.add_argument("account")
    std_args.add_argument('--tty', action='store_true', default=False,
                          help="Allow input from a tty (default=False)")

    #=====
    rndrcmd = sp.add_parser("render", parents=[std_args],
                            description=render_rules.__doc__)
    rndrcmd.add_argument("vars_files", nargs="*", metavar="FILE", default=[])
    rndrcmd.set_defaults(do=render_rules)

    #=====
    rvrscmd = sp.add_parser("reverse", parents=[std_args],
                            description=reverse_rules.__doc__)
    rvrscmd.add_argument("--vars-files", nargs="*", metavar="VARS_FILE", default=[])
    rvrscmd.add_argument("--input-files", nargs="+", metavar="RULES_FILE", default=[])
    rvrscmd.set_defaults(do=reverse_rules)

    return ap
Пример #11
0
def main():
    '''Parse command-line arguments and execute bumpversion command.'''

    parser = ArgumentParser(prog='bumpversion',
                            description='Bumpversion wrapper')

    default_changelog = os.path.join(os.getcwd(), 'CHANGES.rst')

    subparsers = parser.add_subparsers(title='bumpversion wrapper commands')
    # release command
    release_doc = bump_release_version.__doc__
    subparser = subparsers.add_parser("release",
                                      description=release_doc,
                                      formatter_class=RawTextHelpFormatter)
    subparser.add_argument('--changelog', help='Project changelog',
                           type=FileType(),
                           default=default_changelog)
    subparser.set_defaults(func=bump_release_version)
    # newversion command
    newversion_doc = bump_new_version.__doc__
    subparser = subparsers.add_parser("newversion",
                                      description=newversion_doc,
                                      formatter_class=RawTextHelpFormatter)
    subparser.add_argument('--changelog', help='Project changelog',
                           type=FileType(),
                           default=default_changelog)
    subparser.add_argument('part', help='Part of the version to be bumped',
                           choices=['patch', 'minor', 'major'])
    subparser.set_defaults(func=bump_new_version)
    # Parse argv arguments
    args = parser.parse_args()
    args.func(args)
Пример #12
0
    def __new__(mcs, name, bases, attrs):
        instance = super(Commando, mcs).__new__(mcs, name, bases, attrs)
        subcommands = []
        main_command = None
        for name, member in attrs.iteritems():
            if hasattr(member, "command"):
                main_command = member
            elif hasattr(member, "subcommand"):
                subcommands.append(member)
        main_parser = None

        def add_arguments(parser, params):
            """
            Adds parameters to the parser
            """
            for parameter in params:
                parser.add_argument(*parameter.args, **parameter.kwargs)

        if main_command:
            main_parser = ArgumentParser(*main_command.command.args,
                                        **main_command.command.kwargs)
            add_arguments(main_parser, main_command.params)
            subparsers = None
            if len(subcommands):
                subparsers = main_parser.add_subparsers()
                for sub in subcommands:
                    parser = subparsers.add_parser(*sub.subcommand.args,
                                                  **sub.subcommand.kwargs)
                    parser.set_defaults(run=sub)
                    add_arguments(parser, sub.params)

        instance.__parser__ = main_parser
        instance.__main__ = main_command
        return instance
Пример #13
0
def get_option_parser():
    """Return the option parser for this program."""
    parser = ArgumentParser(description="Manage objects in Azure blob storage")
    parser.add_argument(
        '--account-name',
        default=os.environ.get('AZURE_STORAGE_ACCOUNT', None),
        help="The azure storage account, or env AZURE_STORAGE_ACCOUNT.")
    parser.add_argument(
        '--account-key',
        default=os.environ.get('AZURE_STORAGE_ACCESS_KEY', None),
        help="The azure storage account, or env AZURE_STORAGE_ACCESS_KEY.")
    subparsers = parser.add_subparsers(help='sub-command help', dest='command')
    for command in (LIST, PUBLISH, DELETE):
        subparser = subparsers.add_parser(command, help='Command to run')
        subparser.add_argument(
            'purpose', help="<{}>".format(' | '.join(PURPOSES)))
        if command == PUBLISH:
            subparser.add_argument('path', help='The path to publish')
            add_mutation_args(subparser, 'Do not publish')
        elif command == DELETE:
            subparser.add_argument('path', nargs="+",
                                   help='The files to delete')
            add_mutation_args(subparser, 'Do not delete')
    sync_parser = subparsers.add_parser('sync',
                                        help='Sync local files to remote.')
    sync_parser.add_argument('local_dir', metavar='LOCAL-DIR',
                             help='The local directory to sync')
    sync_parser.add_argument('prefix', metavar='PREFIX',
                             help='The remote prefix to sync to')
    add_mutation_args(sync_parser, 'Do not sync')
    return parser
Пример #14
0
def setup():
    parser = ArgumentParser(description='Create starting configs for a slimta instance.')
    parser.add_argument('--version', action='version', version='%(prog)s '+__version__)
    parser.add_argument('-f', '--force', action='store_true', default=False,
                           help='Force overwriting files if destination exists. The user is prompted by default.')
    subparsers = parser.add_subparsers(help='Sub-command Help')

    config_parser = subparsers.add_parser('config', help='Setup Configuration')
    config_parser.add_argument('-e', '--etc-dir', metavar='DIR', default=None,
                           help='Place new configs in DIR. By default, this script will prompt the user for a directory.')
    config_parser.set_defaults(action='config')

    init_parser = subparsers.add_parser('init', help='Setup Init Scripts')
    init_parser.add_argument('-t', '--type', required=True, choices=['lsb', 'systemd'],
                           help='Type of init script to create.')
    init_parser.add_argument('-n', '--name', metavar='NAME', default='slimta',
                           help='Use NAME as the name of the service, default \'%(default)s\'.')
    init_parser.add_argument('-c', '--config-file', metavar='FILE', required=True,
                           help='Use FILE as the slimta configuration file in the init script.')
    init_parser.add_argument('-d', '--daemon', required=True,
                           help='Use DAEMON as the command to execute in the init script.')
    init_parser.add_argument('--init-dir', metavar='DIR', default=None,
                           help='Put resulting init script in DIR instead of the system default.')
    init_parser.add_argument('--pid-dir', metavar='DIR', default='/var/run',
                           help='Put pid files in DIR, default %(default)s.')
    init_parser.add_argument('--enable', action='store_true',
                           help='Once the init script is created, enable it.')
    init_parser.set_defaults(action='init')

    args = parser.parse_args()

    if args.action == 'config':
        _setup_configs(args)
    elif args.action == 'init':
        _setup_inits(args)
Пример #15
0
def setup_parser():
    """Setup an object of class ArgumentParser and return it."""

    root_parser = ArgumentParser()
    root_parser.add_argument(
        '--version',
        action='version',
        version=__version__)

    file_parser = ArgumentParser(add_help=False)
    file_parser.add_argument(
        'file',
        metavar='FILE',
        nargs='?',
        type=FileType('r', encoding='utf-8'),
        help='JSON')

    subparsers = root_parser.add_subparsers(help='commands')
    parser = subparsers.add_parser(
        'twmods',
        parents=[file_parser],
        help='generate both skeleton scripts and modules for twmods')
    parser.set_defaults(func=twmods)

    parser = subparsers.add_parser(
        'pttdemo',
        parents=[file_parser],
        help='generate scripts for PTT demonstration')
    parser.set_defaults(func=pttdemo)

    return root_parser
Пример #16
0
def _parse_arguments():
    parser = ArgumentParser(
        prog='YATUFC',
        description='This program can crawl a given Twitter user timeline '
        'or simply search for a provided term, in order to output found tweets '
        'in a CSV file for further analysis. Also, it is possible to set a date '
        'range for which you are interested, therefore capturing only tweets in '
        'the desired timeslot.',
        epilog='ATTENTION: Twitter API is rate limited. The rates per endpoint '
        'are described in https://developer.twitter.com/en/docs/basics/rate-limits. '
        'If YATUFC hits one of those limits, it\'ll sleep for 15 minutes after when '
        'they\'re finally reset.')
    parser.add_argument(
        '-s', '--since', type=_create_date, required=False,
        default='0001-1-1', metavar='YEAR-MONTH-DAY',
        help='a date in the format YEAR-MONTH-DAY (default: no limit)')
    parser.add_argument(
        '-u', '--upTo', type=_create_date, required=False,
        default=date.today().isoformat(), metavar='YEAR-MONTH-DAY',
        help='a date in the format YEAR-MONTH-DAY (default: now)')
    parser.add_argument(
        '-o', '--outputFilePath', type=str, required=False,
        metavar='outputFilePath', default='output.csv',
        help='a path to save the output data (default: output.csv)')

    subparsers = parser.add_subparsers(help='sub-command help', dest='command')
    parser_profile = subparsers.add_parser('profile')
    parser_profile.add_argument('profileName', metavar='the profile name to crawl.')

    parser_search = subparsers.add_parser('search')
    parser_search.add_argument('searchTerm', metavar='the search term to crawl.')

    return parser.parse_args()
Пример #17
0
def create_parser(defaults):
    description = """
Manage monitors and alert contacts at UptimeRobot.com

If file exists, application will take defaults from:
    ./.uptimerobot.yml
    ~/.uptimerobot.yml
    """

    parser = ArgumentParser(description=description,
                            formatter_class=RawTextHelpFormatter,
                            usage="uptimerobot [-h] SUBCOMMAND [OPTION, ...]")
    sub_commands = parser.add_subparsers(title='Subcommands',
                                         dest="subcommand")

    api_key = defaults["api_key"]

    parse_get_monitors(sub_commands, defaults["get_monitors"], api_key)
    parse_new_monitor(sub_commands, defaults["new_monitor"], api_key)
    parse_edit_monitor(sub_commands, defaults["edit_monitor"], api_key)
    parse_delete_monitor(sub_commands, api_key)

    parse_get_alerts(sub_commands, defaults["get_alerts"], api_key)
    parse_new_alert(sub_commands, defaults["new_alert"], api_key)
    parse_delete_alert(sub_commands, api_key)

    return parser
Пример #18
0
class InspektorApp(object):

    """
    Basic inspektor application.
    """

    def __init__(self):
        self.arg_parser = ArgumentParser(description='Inspektor code check')
        self.arg_parser.add_argument('-v', '--verbose', action='store_true',
                                     help=('print extra debug messages '
                                           '(alters behavior of the lint '
                                           'subcommand)'),
                                     dest='verbose')
        self.arg_parser.add_argument('--exclude', type=str,
                                     help='Quoted string containing paths or '
                                          'patterns to be excluded from '
                                          'checking, comma separated')
        subparsers = self.arg_parser.add_subparsers(title='subcommands',
                                                    description='valid subcommands',
                                                    help='subcommand help')
        lint.set_arguments(subparsers)
        reindent.set_arguments(subparsers)
        style.set_arguments(subparsers)
        check.set_arguments(subparsers)
        license.set_arguments(subparsers)
        self.args = self.arg_parser.parse_args()

    def run(self):
        try:
            return self.args.func(self.args)
        except KeyboardInterrupt:
            log.error('User pressed Ctrl+C, exiting...')
            return ERROR_INTERRUPTED
Пример #19
0
def cli():
    parser_main = ArgumentParser()
    parser_main.set_defaults(func=parser_main.print_usage)
    sub_parsers = parser_main.add_subparsers(help='sub-command')

    # main_parser


    # sub_parser: img
    parser_img = sub_parsers.add_parser('image', help='convert image file format')

    parser_img.add_argument('path', nargs='?', help='image file path')
    parser_img.add_argument('-o', '--outdir', help='output directory')
    parser_img.add_argument('-ext', '--ext',
                            help='to this format like png gif ...')

    parser_img.set_defaults(func=main_img)

    # sub_parser: info
    parser_info = sub_parsers.add_parser('info', help='recognise file format')
    parser_info.add_argument('path', nargs='?', help='file path')

    parser_info.set_defaults(func=main_info)

    parse_result = parser_main.parse_args()
    args = remove_value(remove_key(parse_result.__dict__, 'func'), None)
    try:
        parse_result.func(**args)
    except Exception as ex:
        color.print_err(type(ex), ex)
        color.print_err('Invalid args')
Пример #20
0
def main():
    """
    Tool for generating or simulating economies
    """
    parser = ArgumentParser(version=VERSION, description=main.__doc__)
    subparsers = parser.add_subparsers()

    # Handle the new command
    subparser = subparsers.add_parser('new', help=cmd_new.__doc__)
    subparser.set_defaults(func=cmd_new)

    # Handle the run command
    subparser = subparsers.add_parser('run', help=cmd_run.__doc__)
    subparser.add_argument('-s', '--steps', type=int, default=10000,
            help='Number of steps to simulate (default %(default)d)')
    subparser.add_argument('-i', '--report-interval', type=int, default=100,
            help='Number of steps between reports (default %(default)d)')
    subparser.add_argument('description_file', type=FileType('r'), nargs='+',
            help='One or more YAML files containing economic descriptions to be'
                 'read in order')
    subparser.set_defaults(func=cmd_run)

    # Parse options
    args = parser.parse_args()

    # Initialize logging
    logging.basicConfig(level=logging.INFO)

    # Run command
    args.func(args)
Пример #21
0
def main():
    parser = ArgumentParser(epilog=str_examples())

    #parser.add_argument('--version', action='version', version="ppdojo_db.py " + __version__)

    parser.add_argument('-v', '--verbose', default=0, action='count', # -vv --> verbose=2
                         help='verbose, can be supplied multiple times to increase verbosity')

    # Create the parsers for the sub-commands
    subparsers = parser.add_subparsers(dest='command', help='sub-command help')

    # Subparser for validate command.
    p_validate = subparsers.add_parser('validate', help='Validate the pseudopotential database.')

    # Subparser for regenerate command.
    p_reg = subparsers.add_parser('regenerate', help='Regenerate new checksums.')

    ###################################
    # Parse command line and dispatch #
    ###################################
    options = parser.parse_args()

    verbose = options.verbose

    if options.command == "validate":
        isok = validate_checksums(verbose=verbose)
        print("isok %s " % isok)

    if options.command == "regenerate":
        ans = raw_input("This command will regenerate the md5 hash values. Enter Y to continue... ")
        if ans == "Y":
            regenerate_checksums(verbose=verbose)

    return 0
Пример #22
0
    def _cmd_parse(self):
        """Add command options, add options whthin this method."""
        blade_cmd_help = 'blade <subcommand> [options...] [targets...]'
        arg_parser = ArgumentParser(prog='blade', description=blade_cmd_help)

        sub_parser = arg_parser.add_subparsers(dest="command",
                        help="Available subcommands")

        build_parser = sub_parser.add_parser("build",
                        help="Build specified targets")

        run_parser = sub_parser.add_parser("run",
                        help="Build and runs a single target")

        test_parser = sub_parser.add_parser("test",
                        help="Build the specified targets and runs tests")

        clean_parser = sub_parser.add_parser("clean",
                        help="Remove all Blade-created output")

        query_parser = sub_parser.add_parser("query",
                        help="Execute a dependency graph query")

        self._add_build_arguments(build_parser)
        self._add_build_arguments(run_parser)
        self._add_build_arguments(test_parser)

        self._add_run_arguments(run_parser)
        self._add_test_arguments(test_parser)
        self._add_clean_arguments(clean_parser)
        self._add_query_arguments(query_parser)

        return arg_parser.parse_known_args()
Пример #23
0
    def test_display_completions(self):
        parser = ArgumentParser()
        parser.add_argument("rover",
                            choices=["sojourner", "spirit", "opportunity", "curiosity"],
                            help="help for rover ")
        parser.add_argument("antenna", choices=["low gain", "high gain"], help="help for antenna")
        sub = parser.add_subparsers()
        p = sub.add_parser("list")
        p.add_argument("-o", "--oh", help="ttt")
        p.add_argument("-c", "--ch", help="ccc")
        sub2 = p.add_subparsers()
        sub2.add_parser("cat", help="list cat")
        sub2.add_parser("dog", help="list dog")

        completer = CompletionFinder(parser)

        completer.rl_complete("", 0)
        disp = completer.get_display_completions()
        self.assertEqual("help for rover ", disp.get("spirit", ""))
        self.assertEqual("help for rover ", disp.get("sojourner", ""))
        self.assertEqual("", disp.get("low gain", ""))

        completer.rl_complete('opportunity "low gain" list ', 0)
        disp = completer.get_display_completions()
        self.assertEqual("ttt", disp.get("-o --oh", ""))
        self.assertEqual("list cat", disp.get("cat", ""))

        completer.rl_complete("opportunity low\\ gain list --", 0)
        disp = completer.get_display_completions()
        self.assertEqual("ttt", disp.get("--oh", ""))
        self.assertEqual("ccc", disp.get("--ch", ""))
Пример #24
0
def main():

    parser = ArgumentParser()
    sub_parser = parser.add_subparsers()

    # settings create
    create_parser = sub_parser.add_parser("create", help="create setup.py")
    create_parser.set_defaults(func=create_setuppy)

    # setttings show-classifiers
    show_parser = sub_parser.add_parser(
        "show-classifiers",
        help="show classifiers list"
    )
    show_parser.set_defaults(func=show_classifiers)

    # setup test-env
    test_env_parser = sub_parser.add_parser(
        "setup-test-env",
        help="setup test environment"
    )
    test_env_parser.set_defaults(func=setup_test_environment)

    args = parser.parse_args()

    if hasattr(args, "func"):
        args.func(args)
    else:
        parser.parse_args(["-h"])
Пример #25
0
def create_parser():

    parser = ArgumentParser(description="""
        Tool to interface with rant. Provides methods to create and edit pages
        in yaml/markdown, and generate html sites from them.
    """)

    subparsers = parser.add_subparsers(help='sub-command help', dest='parser')

    subparsers.add_parser(
        'install',
        help='Install a new rant project in current directory'
    )

    subparsers.add_parser(
        'create',
        help='Create a new rant page/post in current directory'
    )

    subparsers.add_parser(
        'build',
        help='Build static site from your source templates and content'
    )

    subparsers.add_parser(
        'serve',
        help='Start server that auto-builds on file-change for development'
    )

    return parser
Пример #26
0
def main():
    """
    """
    parser = ArgumentParser(description="Create a transcription datatest")
    subparsers = parser.add_subparsers(help="subcommand help")

    parser_master = subparsers.add_parser("MASTER", help="master process")
    parser_master.add_argument("command", action="store", help="remote cmd to execute")
    parser_master.set_defaults(type="master")

    parser_worker = subparsers.add_parser("WORKER", help="worker process")
    parser_worker.add_argument("host", action="store", help="name or ip of master host")
    parser_worker.add_argument("port", action="store", help="port number")
    parser_worker.add_argument("command", action="store", help="remote cmd to execute")
    parser_worker.set_defaults(type="worker")

    args = parser.parse_args()
    hostname = socket.getfqdn()
    port = pickUnusedPort()

    if args.type == "master":
        cmd = "{} {} WORKER {} {} '{}'".format(
            sys.executable, os.path.abspath(sys.argv[0]), hostname, port, args.command
        )
        master(port, cmd)

    if args.type == "worker":
        worker(args.host, args.port, args.command)
Пример #27
0
def _get_args():
    parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter,
                            description="Node Agent")
    subparsers = parser.add_subparsers(dest="mode")

    parser_cleanup = subparsers.add_parser('cleanup')
    parser_cleanup.add_argument("session", help="Session Name")
    parser_cleanup.add_argument("volume", help="Volume Name")
    parser_cleanup.add_argument("tmpfilename", help="Temporary File Name")
    parser_cleanup.add_argument("--debug", help="Debug", action="store_true")

    parser_session_create = subparsers.add_parser('create')
    parser_session_create.add_argument("session", help="Session Name")
    parser_session_create.add_argument("volume", help="Volume Name")
    parser_session_create.add_argument("brick", help="Brick Path")
    parser_session_create.add_argument("time_to_update", help="Time to Update")
    parser_session_create.add_argument("--reset-session-time",
                                       help="Reset Session Time",
                                       action="store_true")
    parser_session_create.add_argument("--debug", help="Debug",
                                       action="store_true")

    parser_post = subparsers.add_parser('post')
    parser_post.add_argument("session", help="Session Name")
    parser_post.add_argument("volume", help="Volume Name")
    parser_post.add_argument("brick", help="Brick Path")
    parser_post.add_argument("--debug", help="Debug",
                             action="store_true")

    parser_delete = subparsers.add_parser('delete')
    parser_delete.add_argument("session", help="Session Name")
    parser_delete.add_argument("volume", help="Volume Name")
    parser_delete.add_argument("--debug", help="Debug",
                               action="store_true")
    return parser.parse_args()
Пример #28
0
def parse_cli():
    parser = ArgumentParser(description='Tool for managing laser job recording')

    parser.add_argument(
        'user',
        metavar='USER',
        action='store',
        type=str,
        help='Name of current user')

    subparsers = parser.add_subparsers(help='operation to be performed')

    submit_job_parser = subparsers.add_parser('submit')
    submit_job_parser.set_defaults(which='submit')

    submit_job_parser.add_argument(
        '-t', '--time',
        action='store',
        type=str,
        required=True,
        help='Duration (HH:MM:MM, MM:SS, or SSSS)')

    submit_job_parser.add_argument(
        '-d', '--description',
        action='store',
        type=str,
        help='Optional description of job')

    query_job_parser = subparsers.add_parser('query')
    query_job_parser.set_defaults(which='query')

    #TODO: query stuff

    return parser.parse_args()
Пример #29
0
def main():
    opt_parser = ArgumentParser(
        description="Manage annotation databases of region_analysis.",
        prog="region_analysis_db.py")
    subparsers = opt_parser.add_subparsers(title="Subcommands",
                                           help="additional help")

    # list parser.
    parser_list = subparsers.add_parser("list", help="List genomes installed \
                                                      in database")
    parser_list.set_defaults(func=listgn)

    # install parser.
    parser_install = subparsers.add_parser("install",
                                           help="Install genome from tar.gz \
                                                  package file")
    parser_install.add_argument("pkg", help="Package file(.tar.gz) to install",
                                type=str)
    parser_install.set_defaults(func=install)
    parser_install.add_argument(
        "-y", "--yes", help="Say yes to all prompted questions",
        action="store_true")

    # remove parser.
    parser_remove = subparsers.add_parser("remove",
                                          help="Remove genome from database")
    parser_remove.add_argument("gn", help="Name of genome to be \
                                           removed(e.g. hg19)", type=str)
    parser_remove.set_defaults(func=remove)
    parser_remove.add_argument(
        "-y", "--yes", help="Say yes to all prompted questions",
        action="store_true")

    args = opt_parser.parse_args()
    args.func(args)
Пример #30
0
def main():
    parser = ArgumentParser()
    subs = parser.add_subparsers(dest='cmd')

    account = subs.add_parser('account')
    account.add_argument('--json', '-j', action="store_true",
                         help="Output as JSON")
    sources = subs.add_parser('sources')
    sources.add_argument('--json', '-j', action="store_true",
                         help="Output as JSON")
    organization = subs.add_parser('organization')
    organization.add_argument('--json', '-j', action="store_true",
                              help="Output as JSON")
    args = parser.parse_args()

    client = Client.from_config()
    try:
        if args.cmd == 'account':
            data = client.get_account_details()
        if args.cmd == 'sources':
            data = client.get_account_sources()
        if args.cmd == 'organization':
            data = client.get_account_organization()
    except ValueError as e:
        parser.print_usage()
        sys.stderr.write('{}\n'.format(str(e)))
        sys.exit(1)

    if args.json:
        print(json.dumps(data, indent=4))
    else:
        print(data)