Python argparse.ArgumentParser() Examples

The following are code examples for showing how to use argparse.ArgumentParser(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: quartetsampling   Author: FePhyFoFum   File: merge_output.py    (GNU General Public License v3.0) View Source Project 14 votes vote down vote up
def generate_argparser():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        epilog=LICENSE)
    parser.add_argument('-d', '--nodedata', required=True, nargs=1,
                        help=("file containing paths of one or more"
                              "RESULT.node.score.csv files"))
    parser.add_argument('-t', '--tree', required=True, type=open,
                        nargs=1,
                        help="tree file in Newick format")
    parser.add_argument('-o', '--out', required=True,
                        nargs=1,
                        help="new output files prefix")
    parser.add_argument("-v", "--verbose", action="store_true")
    # These args are hidden to pass through to the treedata object
    parser.add_argument("-c", "--clade", nargs=1, help=argparse.SUPPRESS)
    parser.add_argument("-s", "--startk", type=int, default=0,
                        help=argparse.SUPPRESS)
    parser.add_argument("-p", "--stopk", type=int, help=argparse.SUPPRESS)
    return parser 
Example 2
Project: ekko   Author: openstack   File: backup.py    (Apache License 2.0) View Source Project 10 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description='Backup Block Device')
    parser.add_argument('--backup', required=True,
                        help='Path to backup file or device')
    parser.add_argument('--manifest', required=True,
                        help='manifest file')
    parser.add_argument('--cbt', required=False,
                        help='change block tracking info')
    parser.add_argument('--backend', required=False, default='raw',
                        choices=['raw'], help='backend driver')
    parser.add_argument('--storage', required=False, default='local',
                        choices=['local'], help='storage driver')
    parser.add_argument('--location', required=True, help='storage path')
    parser.add_argument('--driver', required=False, default='sqlite',
                        choices=['osdk', 'sqlite'], help='manifest driver')
    return parser.parse_args() 
Example 3
Project: pygrunt   Author: elementbound   File: run.py    (GNU General Public License v3.0) View Source Project 7 votes vote down vote up
def _parse_args(args):
    parser = argparse.ArgumentParser()

    if any([arg == '--version' for arg in args]):
        return argparse.Namespace(version=True)

    parser.add_argument('script', help='Script to run')
    parser.add_argument('target', nargs='?', default='build', help='Target object to build; defaults to \'build\'')

    parser.add_argument('--version', action='store_true', help='Print version info and exit')
    parser.add_argument('--clear', action='store_true', help='Clear output directory')
    parser.add_argument('--clear-cache', action='store_true', help='Clear cache before compiling')

    parser.add_argument('--threads', '-t', type=int, help='Set thread count; defaults to cores*2')
    parser.add_argument('--no-threading', '-nt', action='store_true', help='Disable multithreaded compiling')

    # TODO: Make target '*' instead of '?' so multiple targets could be ran from the same command

    return parser.parse_args(args) 
Example 4
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
def main():
    """Entry point for creating an application specific security group"""
    logging.basicConfig(format=LOGGING_FORMAT)
    log = logging.getLogger(__name__)

    parser = argparse.ArgumentParser()
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_properties(parser)
    add_region(parser)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    log.debug('Parsed arguments: %s', args)

    spinnakerapps = SpinnakerSecurityGroup(app=args.app, env=args.env, region=args.region, prop_path=args.properties)
    spinnakerapps.create_security_group() 
Example 5
Project: ln2sql   Author: FerreroJeremy   File: main.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def main():
    arg_parser = argparse.ArgumentParser(description='A Utility to convert Natural Language to SQL query')
    arg_parser.add_argument('-d', '--database', help='Path to SQL dump file', required=True)
    arg_parser.add_argument('-l', '--language', help='Path to language configuration file', required=True)
    arg_parser.add_argument('-i', '--sentence', help='Input sentence to parse', required=True)
    arg_parser.add_argument('-j', '--json_output', help='path to JSON output file', default=None)
    arg_parser.add_argument('-t', '--thesaurus', help='path to thesaurus file', default=None)
    arg_parser.add_argument('-s', '--stopwords', help='path to stopwords file', default=None)

    args = arg_parser.parse_args()

    ln2sql = Ln2sql(
        database_path=args.database,
        language_path=args.language,
        json_output_path=args.json_output,
        thesaurus_path=args.thesaurus,
        stopwords_path=args.stopwords,
    ).get_query(args.sentence) 
Example 6
Project: gluster-georep-tools   Author: aravindavk   File: cli.py    (MIT License) View Source Project 6 votes vote down vote up
def get_args():
    """
    Parse the CLI arguments
    """
    parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter,
                            description=PROG_DESCRIPTION)

    parser.add_argument("mastervol", help="Master Volume Name",
                        metavar="MASTERVOL")
    parser.add_argument("slave",
                        help="Slave, HOSTNAME or [email protected]::SLAVEVOL "
                        "or [email protected]::SLAVEVOL",
                        metavar="SLAVE")
    parser.add_argument("--force", help="Force",
                        action="store_true")
    parser.add_argument("--no-color", help="No Terminal Colors",
                        action="store_true")

    return parser.parse_args() 
Example 7
Project: alelo_ofx   Author: dantas   File: main.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def ask_user(preferences = {}):
    def add_argument(name, help, **kwargs):
        kwargs['required'] = kwargs.get('required', not (name in preferences))
        kwargs['default'] = kwargs.get('default', preferences.get(name, None))
        parser.add_argument('--' + name, help=help, **kwargs)

    parser = argparse.ArgumentParser(description="Access MeuAlelo system to extract this month's operations")

    add_argument('cpf', "CPF with only numbers")
    add_argument('password', "Password used to access the system")
    add_argument('card', "Which card from the list we want to access", type=int, default=0)
    add_argument('save', "If present saves the provided configurations in an init file",
        required=False, action="store_true")
    add_argument('month', "Specify for which month transactions must be converted",
        required=False, type=int)

    return vars(parser.parse_args()) 
Example 8
Project: drl.pth   Author: seba-1511   File: utils.py    (license) View Source Project 6 votes vote down vote up
def parse_min_args():
    # Parse arguments
    parser = ArgumentParser()
    parser.add_argument('--expname', '-e', dest='exp', metavar='e', type=str,
                        default='dev', help='Name of the experiment to be run.')
    parser.add_argument('--n_steps', dest='n_steps', type=int,
                        default=300, help='Number of updates to be performed.')
    parser.add_argument('--n_test_iter', dest='n_test_iter', type=int,
                        default=100, help='Number of episodes to test on.')
    parser.add_argument('--update_frequency', dest='update_frequency', type=int,
                        default=1500, help='Number of steps before updating parameters.')
    parser.add_argument('--max_path_length', dest='max_path_length', type=int,
                        default=15000, help='Max length for a trajectory/episode.')
    parser.add_argument('--print_interval', dest='print_interval', type=int,
                        default=1000, help='Number of steps between each print summary.')
    parser.add_argument('--record', dest='record', type=bool,
                        default=False, help='Whether to record videos at test time.')
    parser.add_argument('--render', dest='render', type=bool,
                        default=False, help='Whether to render display at train time.')
    return parser.parse_args() 
Example 9
Project: python-   Author: secondtonone1   File: distro.py    (license) View Source Project 6 votes vote down vote up
def main():
    import argparse

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler(sys.stdout))

    parser = argparse.ArgumentParser(description="Linux distro info tool")
    parser.add_argument(
        '--json',
        '-j',
        help="Output in machine readable format",
        action="store_true")
    args = parser.parse_args()

    if args.json:
        logger.info(json.dumps(info(), indent=4, sort_keys=True))
    else:
        logger.info('Name: %s', name(pretty=True))
        distribution_version = version(pretty=True)
        if distribution_version:
            logger.info('Version: %s', distribution_version)
        distribution_codename = codename()
        if distribution_codename:
            logger.info('Codename: %s', distribution_codename) 
Example 10
Project: nanoQC   Author: wdecoster   File: nanoQC.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def get_args():
    parser = ArgumentParser(
        description="Investigate nucleotide composition and base quality.")
    parser.add_argument("-v", "--version",
                        help="Print version and exit.",
                        action="version",
                        version='NanoQC {}'.format(__version__))
    parser.add_argument("--outdir",
                        help="Specify directory in which output has to be created.",
                        default=".")
    parser.add_argument("-f", "--format",
                        help="Specify the output format of the plots.",
                        default="png",
                        type=str,
                        choices=['eps', 'jpeg', 'jpg', 'pdf', 'pgf', 'png', 'ps',
                                 'raw', 'rgba', 'svg', 'svgz', 'tif', 'tiff'])
    parser.add_argument("fastq",
                        help="Reads data in fastq format.")
    return parser.parse_args() 
Example 11
Project: stack-updater   Author: allatrack   File: cli.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, base_path):
        """
        Initialize CLI arguments
        """
        parser = argparse.ArgumentParser(
            description='Check dependencies by recipe.')
        parser.add_argument('action', choices=['get', 'install', 'check'],
                            default='check', nargs=1,
                            help='get: Download recipe from Gist; \ninstall: '
                                 'Trying to install newer package versions; '
                                 '\ncheck: Simple check')
        parser.add_argument('param', nargs='?',
                            help='Custom recipe directory or gist ID '
                                 'to download recipe')
        parser.add_argument("-v", "--verbose", action="store_true",
                            help="With this flag you can see on the display"
                                 "(not in the log file) "
                                 "triggered command output.")

        self.__cli_args = parser.parse_args()

        self.__base_path = base_path 
Example 12
Project: kas   Author: siemens   File: kas.py    (license) View Source Project 6 votes vote down vote up
def kas_get_argparser():
    """
        Creates a argparser for kas with all plugins.
    """
    parser = argparse.ArgumentParser(description='kas - setup tool for '
                                     'bitbake based project')

    verstr = '%(prog)s {} (configuration format version {}, ' \
        'earliest compatible version {})'.format(__version__, __file_version__,
                                                 __compatible_file_version__)
    parser.add_argument('--version', action='version', version=verstr)

    parser.add_argument('-d', '--debug',
                        action='store_true',
                        help='Enable debug logging')

    subparser = parser.add_subparsers(help='sub command help', dest='cmd')
    for ext_plugin in pkg_resources.iter_entry_points('kas.plugins'):
        ext_plugin.load()

    for plugin in getattr(kasplugin, 'plugins', []):
        plugin.get_argparser(subparser)

    return parser 
Example 13
Project: my-first-blog   Author: AnkurBegining   File: distro.py    (license) View Source Project 6 votes vote down vote up
def main():
    import argparse

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler(sys.stdout))

    parser = argparse.ArgumentParser(description="Linux distro info tool")
    parser.add_argument(
        '--json',
        '-j',
        help="Output in machine readable format",
        action="store_true")
    args = parser.parse_args()

    if args.json:
        logger.info(json.dumps(info(), indent=4, sort_keys=True))
    else:
        logger.info('Name: %s', name(pretty=True))
        distribution_version = version(pretty=True)
        if distribution_version:
            logger.info('Version: %s', distribution_version)
        distribution_codename = codename()
        if distribution_codename:
            logger.info('Codename: %s', distribution_codename) 
Example 14
Project: ImageFudge   Author: Team-Zero-G   File: __main__.py    (MIT License) View Source Project 6 votes vote down vote up
def test_main(args):
    """ """
    parser = argparse.ArgumentParser(description=description())
    parser.add_argument('-f',
                        '--image_file',
                        default='../examples/GodRoss.jpg',
                        type=str,
                        help='The file path of the image to test')
    parser.add_argument('test_name',
                        type=str,
                        help='The name of the test to perform')

    args = parser.parse_args(args)

    try:
        if args.test_name == "test_many_random":
            test_many_random(args.image_file, 5, 5)
        elif args.test_name == "test_multi_origin":
            test_multi_origin(args.image_file, 4)
        else: print("Error: Test function {} doesn't exist".format(args.test_name),
                    file=sys.stderr)
    except OSError:
        print("Error: File: {} doesn't exist".format(args.image_file),
              file=sys.stderr) 
Example 15
Project: vsphere_ansible_inventory   Author: mikesimos   File: vsphere_inventory.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def get_args():
    """
    Return Command Line Arguments.
    :return: ArgumentParser instance
    """
    parser = ArgumentParser(description="vSphere Ansible Inventory.",
                            epilog="Example:\n"
                                   "./vsphere_inventory.py -l\n"
                                   "./vsphere_inventory.py -s <vSphere.hostname>"
                                   "-u <vSphere_username> -p <vSphere_password> -l\n")
    parser.add_argument('-s', '--hostname', help='vSphere vCenter FQDN')
    parser.add_argument('-u', '--username', help='vSphere username')
    parser.add_argument('-p', '--password', help='vSphere password')
    parser.add_argument('-P', '--port', help='vSphere Port')
    parser.add_argument('-c', '--no_cert_check', help='Dont check vSphere certificate', action='store_true')
    parser.add_argument('-g', '--guest', help='Print a single guest')
    parser.add_argument('-x', '--host', help='Print a single guest')
    parser.add_argument('-r', '--reload-cache', help='Reload cache', action='store_true')
    parser.add_argument('-l', '--list', help='List all VMs', action='store_true')

    return parser.parse_args() 
Example 16
Project: picoCTF   Author: picoCTF   File: run.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    """
    Runtime management of the CTF API
    """

    parser = ArgumentParser(description="CTF API configuration")

    parser.add_argument("-v", "--verbose", action="count", help="increase verbosity", default=0)

    parser.add_argument("-p", "--port", action="store", help="port the server should listen on.", type=int, default=8000)
    parser.add_argument("-l", "--listen", action="store", help="host the server should listen on.", default="0.0.0.0")
    parser.add_argument("-d", "--debug", action="store_true", help="run the server in debug mode.", default=False)
    parser.add_argument("-k", "--debug-key", action="store", help="debug key for problem grading; only applies if debug is enabled", type=str, default=None)

    args = parser.parse_args()

    if args.debug:
        api.problem.DEBUG_KEY = args.debug_key

    keyword_args, _ = object_from_args(args)

    api.app.config_app().run(host=args.listen, port=args.port, debug=args.debug) 
Example 17
Project: personal-identification-pipeline   Author: TeamErlich   File: sam-discard-dups.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 18
Project: keras-fractalnet   Author: snf   File: cifar100_fractal.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='FractalNet on CIFAR-100')
    parser.add_argument('--load', nargs=1,
                        help='Test network with weights file')
    parser.add_argument('--deepest', help='Build with only deepest column activated',
                        action='store_true')
    parser.add_argument('--test-all', nargs=1,
                        help='Test all the weights from a folder')
    parser.add_argument('--summary',
                        help='Print a summary of the network and exit',
                        action='store_true')
    args = parser.parse_args()
    net = build_network(deepest=args.deepest)
    if args.load:
        weights = args.load[0]
        test_network(net, weights)
    elif args.test_all:
        folder = args.test_all[0]
        for weights in glob.glob(os.path.join(folder, 'weigh*')):
            test_network(net, weights)
    elif args.summary:
        net.summary()
    else:
        train_network(net) 
Example 19
Project: keras-fractalnet   Author: snf   File: cifar10_fractal.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='FractalNet on CIFAR-10')
    parser.add_argument('--load', nargs=1,
                        help='Test network with weights file')
    parser.add_argument('--deepest', help='Build with only deepest column activated',
                        action='store_true')
    parser.add_argument('--test-all', nargs=1,
                        help='Test all the weights from a folder')
    parser.add_argument('--summary',
                        help='Print a summary of the network and exit',
                        action='store_true')
    args = parser.parse_args()
    net = build_network(deepest=args.deepest)
    if args.load:
        weights = args.load[0]
        test_network(net, weights)
    elif args.test_all:
        folder = args.test_all[0]
        for weights in glob.glob(os.path.join(folder, 'weigh*')):
            test_network(net, weights)
    elif args.summary:
        net.summary()
    else:
        train_network(net) 
Example 20
Project: yolo_tensorflow   Author: hizhangp   File: train.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', default="YOLO_small.ckpt", type=str)
    parser.add_argument('--data_dir', default="data", type=str)
    parser.add_argument('--threshold', default=0.2, type=float)
    parser.add_argument('--iou_threshold', default=0.5, type=float)
    parser.add_argument('--gpu', default='', type=str)
    args = parser.parse_args()

    if args.gpu is not None:
        cfg.GPU = args.gpu

    if args.data_dir != cfg.DATA_PATH:
        update_config_paths(args.data_dir, args.weights)

    os.environ['CUDA_VISIBLE_DEVICES'] = cfg.GPU

    yolo = YOLONet()
    pascal = pascal_voc('train')

    solver = Solver(yolo, pascal)

    print('Start training ...')
    solver.train()
    print('Done training.') 
Example 21
Project: yolo_tensorflow   Author: hizhangp   File: test.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', default="YOLO_small.ckpt", type=str)
    parser.add_argument('--weight_dir', default='weights', type=str)
    parser.add_argument('--data_dir', default="data", type=str)
    parser.add_argument('--gpu', default='', type=str)
    args = parser.parse_args()

    os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu

    yolo = YOLONet(False)
    weight_file = os.path.join(args.data_dir, args.weight_dir, args.weights)
    detector = Detector(yolo, weight_file)

    # detect from camera
    # cap = cv2.VideoCapture(-1)
    # detector.camera_detector(cap)

    # detect from image file
    imname = 'test/person.jpg'
    detector.image_detector(imname) 
Example 22
Project: gee-bridge   Author: francbartoli   File: arguments.py    (license) View Source Project 6 votes vote down vote up
def read_options(fnc, **kwargs):
    """Parse an argparse parser and return an array

    Args:
        fnc (TYPE): Description
        **kwargs: Description

    Returns:
        TYPE: Description
    """
    if isinstance(fnc.__call__(), argparse.ArgumentParser):
        # print argparse2json.convert(fnc.__call__())['widgets']['primary']['contents']
        datas = argparse2json.convert(fnc.__call__())['widgets']['primary']['contents']
        options = []
        for data in datas:
            opts_list = {}
            # print json.dumps(data['data'])
            opts_list['option'] = data['data']
            options.append(opts_list)
        # print 'options', json.dumps(options)
        return options 
Example 23
Project: acbs   Author: AOSC-Dev   File: acbs-build.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 24
Project: data_pipeline   Author: Yelp   File: main.py    (license) View Source Project 6 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(
        description="data_pipeline_introspector provides ability to view the current "
        "state of the data pipeline from a top-down view of namespaces."
    )
    parser.add_argument(
        '--version',
        action='version',
        version="data_pipeline {}".format(__version__)
    )

    subparsers = parser.add_subparsers()
    ListCommandParser.add_parser(subparsers)
    InfoCommandParser.add_parser(subparsers)
    RegisterCommandParser.add_parser(subparsers)
    SchemaCheckCommand.add_parser(subparsers)
    return parser.parse_args() 
Example 25
Project: quartetsampling   Author: FePhyFoFum   File: calc_qstats.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def generate_argparser():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        epilog=LICENSE)
    parser.add_argument('-d', '--data', type=os.path.abspath, nargs=1,
                        required=True,
                        help=("RESULT.node.score.csv file output from"
                              "quartet_sampling.py"))
    parser.add_argument("-c", "--clade", nargs=1,
                        help=("specify a clade using a comma-separated"
                              "list of 2+ descendant taxa"))
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="verbose screen output")
    parser.add_argument("-s", "--startk", type=int, default=0,
                        help="starting branch numerical index")
    parser.add_argument("-p", "--stopk", type=int,
                        help="stopping branch numerical index")
    parser.add_argument("-o", "--out", type=os.path.abspath, nargs=1,
                        help="output file path for statistics")
    return parser 
Example 26
Project: kinect-2-libras   Author: inessadl   File: _uninstall.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _main(argv=None):
    parser = argparse.ArgumentParser(prog="python -m ensurepip._uninstall")
    parser.add_argument(
        "--version",
        action="version",
        version="pip {}".format(ensurepip.version()),
        help="Show the version of pip this will attempt to uninstall.",
    )
    parser.add_argument(
        "-v", "--verbose",
        action="count",
        default=0,
        dest="verbosity",
        help=("Give more output. Option is additive, and can be used up to 3 "
              "times."),
    )

    args = parser.parse_args(argv)

    ensurepip._uninstall_helper(verbosity=args.verbosity) 
Example 27
Project: qqmbr   Author: ischurov   File: qqmathbook.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    argparser = argparse.ArgumentParser()
    argparser.add_argument("command",
                           help="command to invoke: preview or build")
    argparser.add_argument("file",
                           help="File to proceed",
                           default="index.qq",
                           nargs='?')
    argparser.add_argument("--node-mathjax",
                           help="Use server-side mathjax",
                           action='store_true')
    argparser.add_argument('--base-url',
                           help="Base URL")
    argparser.add_argument('--copy-mathjax',
                           help='Copy mathjax files to build/assets',
                           action="store_true")

    args = argparser.parse_args()

    app.config['FILE'] = args.file

    if args.command in commands:
        commands[args.command](**vars(args))
    else:
        print("Unknown command " + args.command) 
Example 28
Project: fccforensics   Author: RagtagOpen   File: bin.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def analyze_command(args):
    parser = argparse.ArgumentParser(description='Analyzes indexes FCC comments')
    parser.add_argument(
        '--endpoint', dest='endpoint',
        default=os.environ.get('ES_ENDPOINT', 'http://127.0.0.1:9200/')
    )
    parser.add_argument(
        '--no-verify', dest='verify', nargs='?',
        help='Don\'t verify SSL certs', default=True,
        const=False
    )
    parser.add_argument(
        '--limit', dest='limit',
        default=10000
    )
    command_args = parser.parse_args(args=args)
    analyzer = CommentAnalyzer(**vars(command_args))
    analyzer.run() 
Example 29
Project: fantasy-dota-heroes   Author: ThePianoDentist   File: add_result_config.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def add_result_config():
    session = make_session()
    parser = argparse.ArgumentParser()
    parser.add_argument("league", type=int, help="league id")
    parser.add_argument("match", type=int, help="match id")
    args = parser.parse_args()
    results = results_config

    with transaction.manager:
        for team in results:
            for player in team['players']:
                result_string = "%s,%s" % (team["position"], player["kills"])
                hero_id = session.query(Hero).filter(Hero.league == args.league).filter(Hero.name == player['name']).first()
                if not hero_id:
                    print "Name wrong"
                    return
                session.add(Result(args.league, hero_id.id, args.match, result_string,
                                   time.time(), 1, 1))
        transaction.commit()
    return 
Example 30
Project: fantasy-dota-heroes   Author: ThePianoDentist   File: add_result.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def add_result():
    session = make_session()

    parser = argparse.ArgumentParser()
    parser.add_argument("league", type=int, help="league id")
    parser.add_argument("match", type=int, help="match")
    parser.add_argument("player", type=str, help="player name")
    parser.add_argument("position", type=int, help="team position")
    parser.add_argument("kills", type=int, help="player kills")

    args = parser.parse_args()
    with transaction.manager:
        result_string = "%s,%s" % (args.position, args.kills)
        hero_id = session.query(Hero).filter(Hero.league == args.league).filter(Hero.name == args.player).first()
        if not hero_id:
            print "Name wrong"
            return
        session.add(Result(args.league, hero_id.id, args.match, result_string,
                           time.time(), 1, 1))
        transaction.commit()
    return 
Example 31
Project: fantasy-dota-heroes   Author: ThePianoDentist   File: update_all.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    session = make_session()
    parser = argparse.ArgumentParser()
    parser.add_argument("league", type=int, help="league id")
    args = parser.parse_args()
    league = session.query(League).filter(League.id == args.league).first()
    with transaction.manager:
        print "Updating hero points"
        update_hero_points(session, league)
        transaction.commit()
    with transaction.manager:
        print "Updating league points"
        update_league_points(session, league)
        transaction.commit()
    with transaction.manager:
        print "Updating user rankings"
        update_user_rankings(session, league)
        transaction.commit() 
Example 32
Project: Fast5-to-Fastq   Author: rrwick   File: fast5_to_fastq.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def get_arguments():
    parser = argparse.ArgumentParser(description='FAST5 to FASTQ',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('dir', type=str,
                        help='directory of FAST5 reads to extract (will be searched recursively)')
    parser.add_argument('--min_length', type=int, default=0,
                        help='Exclude reads shorter than this length (in bp)')
    parser.add_argument('--min_mean_qual', type=float, default=0.0,
                        help='Exclude reads with a mean qscore less than this value')
    parser.add_argument('--min_qual_window', type=float, default=0.0,
                        help='Exclude reads where their mean qscore in a sliding window drops '
                             'below this value')
    parser.add_argument('--window_size', type=int, default=50,
                        help='The size of the sliding window used for --min_qual_window')
    parser.add_argument('--target_bases', type=int, default=None,
                        help='If set, exclude the worst reads (as judged by their minimum qscore '
                             'in a sliding window) such that only this many bases remain')
    args = parser.parse_args()
    args.dir = os.path.abspath(args.dir)
    return args 
Example 33
Project: benzoin   Author: mpilar   File: validation_script.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    """
    Parse arguments and trigger main application
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("--region", help="The region to operate in.", default="us-east-1")
    parser.add_argument("jsondoc", help="The json document describing the snapshot.")
    args = parser.parse_args()
    config = {}
    with open(args.jsondoc, 'r') as jsonf:
        config = json.load(jsonf)
    snapshot_ids = [vol["snapshot-id"] for vol in config.get("backup-volumes")]
    region = config["region"]
    try:
        if are_snapshots_tagged(region, snapshot_ids):
            return
        validate_all_collections()
        update_tags(region, snapshot_ids, True)
    except Exception as exc:
        update_tags(region, snapshot_ids, False)
        #TODO: Add alerting, monitoring, chaos, destruction, etc.
        raise exc 
Example 34
Project: android-backup-tools   Author: bluec0re   File: unpack.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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
                ) 
Example 35
Project: android-backup-tools   Author: bluec0re   File: pack.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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
        ) 
Example 36
Project: freeradius   Author: epiphyte   File: manage.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    """Main entry point."""
    parser = argparse.ArgumentParser()
    parser.add_argument('action',
                        nargs='?',
                        choices=[CHECK, ADD_USER, BUILD, GEN_PSWD],
                        default=CHECK)
    parser.add_argument('--key', type=str)
    args = parser.parse_args()
    key = None
    if args.key:
        key = wrapper.convert_key(args.key)
    if args.action == CHECK:
        check()
    elif args.action == BUILD:
        try:
            build()
        except Exception as e:
            _smirc("build error")
            print(str(e))
    elif args.action == ADD_USER:
        add_user(key)
    elif args.action == GEN_PSWD:
        gen_pass(True, key) 
Example 37
Project: whatstyle   Author: mikr   File: show3diffs.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='Open a diff tool with three files')
    parser.add_argument('filename', nargs='*', help='input filename')
    # The info and debug options were inspired by rsync.
    parser.add_argument('--tool', help='path of diff tool')
    parser.add_argument('--results', action='store_true', help='show results diffs')

    args = parser.parse_args()
    tool = args.tool
    if tool is None:
        tool = os.environ.get(DIFF3_VARNAME)
    if tool is None:
        parser.error('Please specify the 3-way file comparison tool with --tool or set %s' %
                     DIFF3_VARNAME)
    if args.results:
        return modified_results(tool)
    filenames = args.filename
    if not filenames:
        parser.error('Please specify at least one source file')

    filenames = [os.path.abspath(f) for f in filenames]
    diff_for_files(tool, filenames)
    return 0 
Example 38
Project: whatstyle   Author: mikr   File: whatstyle.py    (MIT License) View Source Project 6 votes vote down vote up
def run_with_args(args, parser):
    # type: (argparse.Namespace, argparse.ArgumentParser) -> int
    set_logging_parameters(args, parser)
    start_time = time.time()
    ret = OK
    try:
        if args.profile:
            outline("Profiling...")
            profile("ret = whatstyle(args, parser)", locals(), globals())
        else:
            ret = whatstyle(args, parser)
    except IOError as exc:
        # If the output is piped into a pager like 'less' we get a broken pipe when
        # the pager is quit early and that is ok.
        if exc.errno == errno.EPIPE:
            pass
        elif str(exc) == 'Stream closed':
            pass
        else:
            raise
        if not PY2:
            sys.stderr.close()
    iprint(INFO_TIME, 'Run time: %s seconds' % (time.time() - start_time))
    return ret 
Example 39
Project: run_lambda   Author: ethantkoenig   File: __main__.py    (MIT License) View Source Project 6 votes vote down vote up
def arguments():
    parser = argparse.ArgumentParser(description="Run AWS Lambda function locally")
    parser.add_argument("filename", type=str,
                        help="name of file containing Lambda function")
    parser.add_argument("event", type=str,
                        help="filename of file containing JSON event data")
    parser.add_argument("-f", "--function", metavar="HANDLER_FUNCTION",
                        dest="function_name", type=str, default="handler",
                        help="Name of handler function. Defaults to \"handler\"")
    parser.add_argument("-t", "--timeout", metavar="TIMEOUT",
                        dest="timeout", type=int, default=None,
                        help="Timeout (in seconds) for function call. If not provided, "
                             "no timeout will be used.")
    parser.add_argument("-c", "--context", metavar="CONTEXT_FILENAME", type=str, default=None,
                        dest="context_file",
                        help="Filename of file containing JSON context data")
    return parser.parse_args() 
Example 40
Project: coala-langserver   Author: gaocegege   File: langserver.py    (GNU Affero General Public License v3.0) View Source Project 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description="")
    parser.add_argument("--mode", default="stdio",
                        help="communication (stdio|tcp)")
    parser.add_argument("--addr", default=2087,
                        help="server listen (tcp)", type=int)

    args = parser.parse_args()

    if args.mode == "stdio":
        log("Reading on stdin, writing on stdout")
        s = LangServer(conn=ReadWriter(sys.stdin, sys.stdout))
        s.listen()
    elif args.mode == "tcp":
        host, addr = "0.0.0.0", args.addr
        log("Accepting TCP connections on {}:{}".format(host, addr))
        ThreadingTCPServer.allow_reuse_address = True
        s = ThreadingTCPServer((host, addr), LangserverTCPTransport)
        try:
            s.serve_forever()
        finally:
            s.shutdown() 
Example 41
Project: dl4mt-multi   Author: nyu-dl   File: initialize_model.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def get_parser():

    def dict_type(ss):
        return dict([map(str.strip, s.split(':'))
                     for s in ss.split(',')])

    parser = argparse.ArgumentParser()
    parser.add_argument('--proto', type=str)
    parser.add_argument('--ref-encs', type=dict_type,
                        help="Models to initialize encoders, \
                        eg. --ref-encs=fi:file1,de:file2")
    parser.add_argument('--ref-decs', type=dict_type,
                        help="Models to initialize decoders, \
                        eg. --ref-decs=en:file1,de:file2")
    parser.add_argument('--ref-att', type=str,
                        help="Model to initialize shared components")
    parser.add_argument('--ref-dec-embs', type=dict_type,
                        help="Models to initialize decoder embeddings, \
                        eg. --ref-dec-embs=en:file1,de:file2")
    parser.add_argument('--ref-enc-embs', type=dict_type,
                        help="Models to initialize encoder embeddings, \
                        eg. --ref-enc-embs=en:file1,de:file2")
    return parser 
Example 42
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """Run newer stuffs."""
    logging.basicConfig(format=LOGGING_FORMAT)
    log = logging.getLogger(__name__)

    parser = argparse.ArgumentParser()
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_region(parser)
    add_properties(parser)
    parser.add_argument("--elb-subnet", help="Subnetnet type, e.g. external, internal", required=True)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    log.debug('Parsed arguments: %s', args)

    spinnakerapps = SpinnakerDns(
        app=args.app, env=args.env, region=args.region, prop_path=args.properties, elb_subnet=args.elb_subnet)
    spinnakerapps.create_elb_dns() 
Example 43
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """Destroy any DNS related resources of an application

    Records in any Hosted Zone for an Environment will be deleted.
    """
    logging.basicConfig(format=LOGGING_FORMAT)

    parser = argparse.ArgumentParser(description=main.__doc__)
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    assert destroy_dns(**vars(args)) 
Example 44
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """Command to create IAM Instance Profiles, Roles, Users, and Groups.

    IAM Roles will retain any attached Managed Policies. Inline Policies that do
    not match the name *iam-project_repo_policy* will also be left untouched.

    **WARNING**: Inline Policies named *iam-project_repo_policy* will be
    rewritten.
    """
    logging.basicConfig(format=LOGGING_FORMAT)

    parser = argparse.ArgumentParser(description=main.__doc__)
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    assert create_iam_resources(**args.__dict__) 
Example 45
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """Append Application Configurations to a given file in multiple formats."""
    logging.basicConfig(format=LOGGING_FORMAT)

    parser = argparse.ArgumentParser(description=main.__doc__)
    add_debug(parser)
    parser.add_argument('-o', '--output', required=True, help='Name of environment file to append to')
    parser.add_argument(
        '-g', '--git-short', metavar='GROUP/PROJECT', required=True, help='Short name for Git, e.g. forrest/core')
    parser.add_argument('-r', '--runway-dir', help='Runway directory with app.json files, requires --git-short')
    args = parser.parse_args()

    LOG.setLevel(args.debug)
    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    generated = gogoutils.Generator(*gogoutils.Parser(args.git_short).parse_url(), formats=APP_FORMATS)
    git_short = generated.gitlab()['main']

    if args.runway_dir:
        configs = process_runway_configs(runway_dir=args.runway_dir)
    else:
        configs = process_git_configs(git_short=git_short)

    write_variables(app_configs=configs, out_file=args.output, git_short=git_short) 
Example 46
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """CLI entrypoint for scaling policy creation"""
    logging.basicConfig(format=LOGGING_FORMAT)
    log = logging.getLogger(__name__)

    parser = argparse.ArgumentParser()
    add_debug(parser)
    add_app(parser)
    add_properties(parser)
    add_env(parser)
    add_region(parser)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    log.debug('Parsed arguments: %s', args)

    asgpolicy = AutoScalingPolicy(app=args.app, prop_path=args.properties, env=args.env, region=args.region)

    asgpolicy.create_policy() 
Example 47
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """Entry point for ELB creation"""
    logging.basicConfig(format=LOGGING_FORMAT)

    parser = argparse.ArgumentParser(description='Example with non-optional arguments')

    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_region(parser)
    add_properties(parser)

    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    elb = SpinnakerELB(app=args.app, env=args.env, region=args.region, prop_path=args.properties)
    elb.create_elb() 
Example 48
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """Send Slack notification to a configured channel."""
    logging.basicConfig(format=LOGGING_FORMAT)
    log = logging.getLogger(__name__)

    parser = argparse.ArgumentParser()
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_properties(parser)

    args = parser.parse_args()

    logging.getLogger(__package__.split(".")[0]).setLevel(args.debug)
    log.debug('Parsed arguements: %s', args)

    if "prod" not in args.env:
        log.info('No slack message sent, not a production environment')
    else:
        log.info("Sending slack message, production environment")
        slacknotify = SlackNotification(app=args.app, env=args.env, prop_path=args.properties)
        slacknotify.post_message() 
Example 49
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """Create Lambda events."""
    logging.basicConfig(format=LOGGING_FORMAT)
    log = logging.getLogger(__name__)

    parser = argparse.ArgumentParser(description=main.__doc__)
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_properties(parser)
    add_region(parser)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    log.debug('Parsed arguments: %s', args)

    lambda_function = LambdaFunction(app=args.app, env=args.env, region=args.region, prop_path=args.properties)

    lambda_function.create_lambda_function()

    lambda_event = LambdaEvent(app=args.app, env=args.env, region=args.region, prop_path=args.properties)
    lambda_event.create_lambda_events() 
Example 50
Project: foremast   Author: gogoair   File: __main__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def main():
    """Create any API Gateway event related resources."""
    logging.basicConfig(format=LOGGING_FORMAT)

    parser = argparse.ArgumentParser(description=main.__doc__)
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_region(parser)
    add_properties(parser)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    apigateway = APIGateway(**vars(args))
    apigateway.setup_lambda_api()