Python argparse.RawTextHelpFormatter() Examples

The following are code examples for showing how to use argparse.RawTextHelpFormatter(). 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: kAFL   Author: RUB-SysSec   File: config.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def __load_arguments(self):
        parser = ArgsParser(formatter_class=argparse.RawTextHelpFormatter)

        parser.add_argument('ram_file', metavar='<RAM File>', action=FullPaths, type=parse_is_file,
                            help='path to the RAM file.')
        parser.add_argument('overlay_dir', metavar='<Overlay Directory>', action=FullPaths, type=parse_is_dir,
                            help='path to the overlay directory.')
        parser.add_argument('executable', metavar='<Info Executable>', action=FullPaths, type=parse_is_file,
                            help='path to the info executable (kernel address dumper).')
        parser.add_argument('mem', metavar='<RAM Size>', help='size of virtual RAM (default: 300).', default=300, type=int)

        parser.add_argument('-v', required=False, help='enable verbose mode (./debug.log).', action='store_true',
                            default=False)
        parser.add_argument('-S', required=False, metavar='Snapshot', help='specifiy snapshot title (default: kafl).', default="kafl", type=str)
        parser.add_argument('-macOS', required=False, help='enable macOS Support (requires Apple OSK)', action='store_true', default=False)

        self.argument_values = vars(parser.parse_args()) 
Example 2
Project: GeneGAN   Author: Prinsphield   File: train.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='test', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument(
        '-a', '--attribute', 
        default='Smiling',
        type=str,
        help='Specify attribute name for training. \ndefault: %(default)s. \nAll attributes can be found in list_attr_celeba.txt'
    )
    parser.add_argument(
        '-g', '--gpu', 
        default='0',
        type=str,
        help='Specify GPU id. \ndefault: %(default)s. \nUse comma to seperate several ids, for example: 0,1'
    )
    args = parser.parse_args()

    celebA = Dataset(args.attribute)
    GeneGAN = Model(is_train=True)
    run(config, celebA, GeneGAN, gpu=args.gpu) 
Example 3
Project: confu   Author: Maratyszcza   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def standard_parser(description="Confu configuration script"):
    import argparse

    from os import linesep
    from confu.platform import host, possible_targets

    parser = argparse.ArgumentParser(description=description,
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("--target", dest="target", metavar="PLATFORM", type=Platform,
        default=host.name,
        help="platform where the code will run. Potential options:" + linesep +
            "    " + host.name + " (default)" + linesep +
            linesep.join("    " + target for target in possible_targets[1:]))
    parser.add_argument("--toolchain", dest="toolchain", metavar="TOOLCHAIN",
        choices=["auto", "gnu", "clang"], default="auto",
        help="toolchain to use for compilation. Potential options:" + linesep +
            linesep.join("    " + name for name in ["auto (default)", "gnu", "clang"]))

    

    return parser 
Example 4
Project: cligenerator   Author: bharadwaj-raju   File: cli_module.py    (license) View Source Project 6 votes vote down vote up
def __init__(self):

		parser = argparse.ArgumentParser(
			description='A CLI tool for mymodule',
			formatter_class=argparse.RawTextHelpFormatter,
			usage='%(prog)s command options',
			allow_abbrev=False)

		parser.add_argument('command', help='Command to run.')

		args = parser.parse_args(sys.argv[1:2])  # Ignore options

		self._one_func_mode = False

		if not hasattr(self, args.command.replace('.', '_')):
			print('Unrecognized command!')
			sys.exit(1)

		getattr(self, args.command.replace('.', '_'))() 
Example 5
Project: pynsxv   Author: vmware   File: nsx_logical_switch.py    (license) View Source Project 6 votes vote down vote up
def contruct_parser(subparsers):
    parser = subparsers.add_parser('lswitch', description="Functions for logical switches",
                                   help="Functions for logical switches",
                                   formatter_class=RawTextHelpFormatter)

    parser.add_argument("command", help="""
    create: create a new logical switch
    read:   return the virtual wire id of a logical switch
    delete: delete a logical switch"
    list:   return a list of all logical switches
    """)

    parser.add_argument("-t",
                        "--transport_zone",
                        help="nsx transport zone")
    parser.add_argument("-n",
                        "--name",
                        help="logical switch name, needed for create, read and delete")

    parser.set_defaults(func=_lswitch_main) 
Example 6
Project: panels   Author: grimoirelab   File: owlwatch.py    (license) View Source Project 6 votes vote down vote up
def parse_args():
    """Parse arguments from the command line"""
    parser = argparse.ArgumentParser(description=DESC_MSG,
                                     formatter_class=RawTextHelpFormatter)

    group_exc = parser.add_mutually_exclusive_group(required=False)
    group_exc.add_argument('-g', '--debug', dest='debug', action='store_true')
    group_exc.add_argument('-l', '--info', dest='info', action='store_true')

    parser.add_argument('-v', '--version', action='version',
                        version='%(prog)s ' + VERSION)

    subparsers = parser.add_subparsers(dest='subparser_name')
    add_mapping_subparser(subparsers)
    add_panel_subparser(subparsers)
    add_csv_subparser(subparsers)

    return parser.parse_args() 
Example 7
Project: har2warc   Author: webrecorder   File: har2warc.py    (license) View Source Project 6 votes vote down vote up
def main(args=None):
    parser = ArgumentParser(description='HAR to WARC Converter',
                            formatter_class=RawTextHelpFormatter)

    parser.add_argument('input')
    parser.add_argument('output')

    parser.add_argument('--title')
    parser.add_argument('--no-z', action='store_true')
    parser.add_argument('-v', '--verbose', action='store_true')

    r = parser.parse_args(args=args)

    rec_title = r.title or r.input.rsplit('/', 1)[-1]

    logging.basicConfig(format='[%(levelname)s]: %(message)s')
    HarParser.logger.setLevel(logging.ERROR if not r.verbose else logging.INFO)

    with open(r.output, 'wb') as fh:
        writer = WARCWriter(fh, gzip=not r.no_z)
        HarParser(r.input, writer).parse(r.output, rec_title) 
Example 8
Project: mic_array   Author: respeaker   File: google_assistant_for_raspberry_pi.py    (license) View Source Project 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--credentials', type=existing_file,
                        metavar='OAUTH2_CREDENTIALS_FILE',
                        default=os.path.join(
                            os.path.expanduser('~/.config'),
                            'google-oauthlib-tool',
                            'credentials.json'
                        ),
                        help='Path to store and read OAuth2 credentials')
    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))

    with Assistant(credentials) as assistant:
        for event in assistant.start():
            process_event(event) 
Example 9
Project: flowsynth   Author: secureworks   File: flowsynth.py    (license) View Source Project 6 votes vote down vote up
def parse_cmd_line():
    """ use ArgumentParser to parse command line arguments """

    app_description = "FlowSynth v%s\nWill Urbanski <[email protected]>\n\na tool for rapidly modeling network traffic" % APP_VERSION_STRING

    parser = argparse.ArgumentParser(description=app_description, formatter_class = argparse.RawTextHelpFormatter)
    parser.add_argument('input', help='input files')
    parser.add_argument('-f', dest='output_format', action='store', default="hex",
        help='Output format. Valid output formats include: hex, pcap')
    parser.add_argument('-w', dest='output_file', action='store', default="", help='Output file.')
    parser.add_argument('-q', dest='quiet', action='store_true', default=False, help='Run silently')
    parser.add_argument('-d', dest='debug', action='store_true', default=False, help='Run in debug mode')
    parser.add_argument('--display', dest='display', action='store', default='text', choices=['text','json'], help='Display format')
    parser.add_argument('--no-filecontent', dest='no_filecontent', action='store_true', default=False, help='Disable support for the filecontent attribute')

    args = parser.parse_args()

    if (args.quiet == True):
        LOGGING_LEVEL = logging.CRITICAL
    if (args.debug == True):
        LOGGING_LEVEL = logging.DEBUG

    return args 
Example 10
Project: cluster-genesis   Author: open-power-ref-design-toolkit   File: allocate_ip_addresses.py    (license) View Source Project 6 votes vote down vote up
def main():

    parser = argparse.ArgumentParser(
        description=('Allocates IP addresses on nodes in an inventory file.'),
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('--inventory',
                        dest='inventory_file',
                        required=True,
                        help='The path to the inventory file.')

    # Handle error cases before attempting to parse
    # a command off the command line
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)
    args = parser.parse_args()

    allocate_ips(args.inventory_file) 
Example 11
Project: Intranet-Penetration   Author: yuxiaokui   File: cli.py    (license) View Source Project 6 votes vote down vote up
def parse_argument(argv=None):
    parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
    parser.set_defaults(body=None, headers={})
    make_positional_argument(parser)
    make_troubleshooting_argument(parser)
    args = parser.parse_args(sys.argv[1:] if argv is None else argv)

    if args.debug:
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        log.addHandler(handler)
        log.setLevel(logging.DEBUG)

    set_url_info(args)
    set_request_data(args)
    return args 
Example 12
Project: MKFQ   Author: maojingios   File: cli.py    (license) View Source Project 6 votes vote down vote up
def parse_argument(argv=None):
    parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
    parser.set_defaults(body=None, headers={})
    make_positional_argument(parser)
    make_troubleshooting_argument(parser)
    args = parser.parse_args(sys.argv[1:] if argv is None else argv)

    if args.debug:
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        log.addHandler(handler)
        log.setLevel(logging.DEBUG)

    set_url_info(args)
    set_request_data(args)
    return args 
Example 13
Project: hls-to-dash   Author: Eyevinn   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def main():
    version = pkg_resources.require('hls2dash')[0].version
    parser = argparse.ArgumentParser(
        description="Rewrap a MPEG2 TS segment to a fragmented MP4"
        ,formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('tsfile', metavar='TSFILE', help='Path to TS file. Can be a URI or local file.')
    parser.add_argument('output', metavar='OUTPUT', help='Output file name')
    parser.add_argument('--outdir', dest='outdir', default='.', help='Directory where the fragmented MP4 will be stored. Default is current directory')
    parser.add_argument('--debug', dest='debug', action='store_true', default=False, help='Write debug info to stderr')
    parser.add_argument('--version', action='version', version='%(prog)s ('+version+')')
    args = parser.parse_args()
    debug.doDebug = args.debug

    ts = None
    if re.match('^http', args.tsfile):
        ts = TS.Remote(args.tsfile)
    else:
        ts = TS.Local(args.tsfile)
    ts.remuxMP4(args.outdir, args.output) 
Example 14
Project: hls-to-dash   Author: Eyevinn   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def main():
    version = VERSION()
    parser = argparse.ArgumentParser(
        description="Generate single and multi period MPEG DASH manifest from a live HLS source.\n" 
                    "Writes MPEG DASH manifest to stdout.\n\n"
                    "Currently assumes that HLS variant is named as 'master[PROFILE].m3u8'\n" 
                    "  master2500.m3u8, master1500.m3u8\n"
                    "and that the segments are named as 'master[PROFILE]_[SEGNO].ts'\n"
                    "  master2500_34202.ts, master1500_34202.ts\n" 
        ,formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('playlist', metavar='PLAYLIST', help='Path to HLS playlist file. Can be a URI or local file.')
    parser.add_argument('--multi', dest='multi', action='store_true', default=False, help='Generate multi period MPEG DASH on EXT-X-CUE markers in HLS')
    parser.add_argument('--ctx', dest='ctx', default=None, help='Name of DASH session file')
    parser.add_argument('--ctxdir', dest='ctxdir', default='/tmp/', help='Where to store DASH session file. Defaults to /tmp/')
    parser.add_argument('--debug', dest='debug', action='store_true', default=False, help='Write debug info to stderr')
    parser.add_argument('--version', action='version', version='%(prog)s ('+version+')')
    args = parser.parse_args()
    debug.doDebug = args.debug

    mpd = MPD.HLS(args.playlist, args.multi, args.ctxdir, args.ctx)
    mpd.setVersion(VERSION())
    mpd.load()
    print(mpd.asXML()) 
Example 15
Project: nittygriddy   Author: cbourjau   File: parser.py    (license) View Source Project 6 votes vote down vote up
def create_parser():
    """
    Creates the parser object

    By using a function, the parser is also easily available for unittests
    """
    class formatter_class(argparse.ArgumentDefaultsHelpFormatter,
                          argparse.RawTextHelpFormatter):
        pass

    parser = argparse.ArgumentParser(formatter_class=formatter_class)
    parser.add_argument(
        '-v', '--verbose', action='store_true', default=False)
    subparsers = parser.add_subparsers()
    run.create_subparsers(subparsers)
    merge.create_subparsers(subparsers)
    datasets.create_subparser(subparsers)
    new.create_subparsers(subparsers)
    profile.create_subparsers(subparsers)
    return parser 
Example 16
Project: MDT   Author: cbclab   File: mdt_info_protocol.py    (license) View Source Project 6 votes vote down vote up
def _get_arg_parser(self, doc_parser=False):
        description = textwrap.dedent(__doc__)

        examples = textwrap.dedent('''
            mdt-info-protocol my_protocol.prtcl
           ''')
        epilog = self._format_examples(doc_parser, examples)

        parser = argparse.ArgumentParser(description=description, epilog=epilog,
                                         formatter_class=argparse.RawTextHelpFormatter)

        parser.add_argument('protocol',
                            action=mdt.shell_utils.get_argparse_extension_checker(['.prtcl']),
                            help='the protocol file').completer = FilesCompleter(['prtcl'], directories=False)

        return parser 
Example 17
Project: MDT   Author: cbclab   File: mdt_view_maps.py    (license) View Source Project 6 votes vote down vote up
def _get_arg_parser(self, doc_parser=False):
        description = textwrap.dedent(__doc__)

        parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawTextHelpFormatter)
        parser.add_argument('items', metavar='items', type=str, nargs='*', help='the directory or file(s)',
                            default=None).completer = FilesCompleter()

        parser.add_argument('-c', '--config', type=str,
                            help='Use the given initial configuration').completer = \
            FilesCompleter(['conf'], directories=False)

        parser.add_argument('-m', '--maximize', action='store_true', help="Maximize the shown window")
        parser.add_argument('--to-file', type=str, help="If set export the figure to the given filename")

        parser.add_argument('--width', type=int, help="The width of the output file when --to-file is set")
        parser.add_argument('--height', type=int, help="The height of the output file when --to-file is set")
        parser.add_argument('--dpi', type=int, help="The dpi of the output file when --to-file is set")

        return parser 
Example 18
Project: MDT   Author: cbclab   File: mdt_info_img.py    (license) View Source Project 6 votes vote down vote up
def _get_arg_parser(self, doc_parser=False):
        description = textwrap.dedent(__doc__)

        examples = textwrap.dedent('''
            mdt-info-img my_img.nii
            mdt-info-img *.nii
           ''')
        epilog = self._format_examples(doc_parser, examples)

        parser = argparse.ArgumentParser(description=description, epilog=epilog,
                                         formatter_class=argparse.RawTextHelpFormatter)

        parser.add_argument('images', metavar='images', nargs="+", type=str,
                            help="The input images")

        return parser 
Example 19
Project: MDT   Author: cbclab   File: mdt_apply_mask.py    (license) View Source Project 6 votes vote down vote up
def _get_arg_parser(self, doc_parser=False):
        description = textwrap.dedent(__doc__)

        examples = textwrap.dedent('''
            mdt-apply-mask data.nii.gz -m roi_mask_0_50.nii.gz
            mdt-apply-mask *.nii.gz -m my_mask.nii.gz
        ''')
        epilog = self._format_examples(doc_parser, examples)

        parser = argparse.ArgumentParser(description=description, epilog=epilog,
                                         formatter_class=argparse.RawTextHelpFormatter)

        parser.add_argument('mask', help='the (brain) mask to use').completer = \
            FilesCompleter(['nii', 'gz', 'hdr', 'img'], directories=False)

        parser.add_argument('input_files', metavar='input_files', nargs="+", type=str,
                            help="The input images to use")

        parser.add_argument('--overwrite', dest='overwrite', action='store_true',
                            help="Overwrite the original images, if not set we create an output file.")
        parser.set_defaults(overwrite=False)

        return parser 
Example 20
Project: MDT   Author: cbclab   File: mdt_generate_bvec_bval.py    (license) View Source Project 6 votes vote down vote up
def _get_arg_parser(self, doc_parser=False):
        description = textwrap.dedent(__doc__)

        examples = textwrap.dedent('''
            mdt-generate-bvec-bval my_protocol.prtcl
            mdt-generate-bvec-bval my_protocol.prtcl bvec_name.bvec bval_name.bval
        ''')
        epilog = self._format_examples(doc_parser, examples)

        parser = argparse.ArgumentParser(description=description, epilog=epilog,
                                         formatter_class=argparse.RawTextHelpFormatter)

        parser.add_argument('protocol', help='the protocol file').completer = FilesCompleter()
        parser.add_argument('bvec', help="the output bvec file", nargs='?', default=None).completer = FilesCompleter()
        parser.add_argument('bval', help="the output bvec file", nargs='?', default=None).completer = FilesCompleter()

        return parser 
Example 21
Project: aetros-cli   Author: aetros   File: PullJobCommand.py    (license) View Source Project 6 votes vote down vote up
def main(self, args):
        import aetros.const

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' pull-job')
        parser.add_argument('id', nargs='?', help="Model name like peter/mnist/ef8009d83a9892968097cec05b9467c685d45453")

        parsed_args = parser.parse_args(args)

        if not parsed_args.id:
            parser.print_help()
            sys.exit(1)

        config = read_home_config()
        model = parsed_args.id[0:parsed_args.id.rindex('/')]
        ref = 'refs/aetros/job/' + parsed_args.id[parsed_args.id.rindex('/')+1:]

        git_dir = os.path.normpath(config['storage_dir'] + '/' + model + '.git')

        if not os.path.isdir(git_dir):
            self.logger.error("Git repository for model %s in %s not found." % (parsed_args.id, git_dir))
            self.logger.error("Are you in the correct directory?")

        print('Pull ' + ref + ' into ' + git_dir)
        setup_git_ssh(config)
        subprocess.call([config['git'], '--bare', '--git-dir', git_dir, 'fetch', 'origin', ref+':'+ref]) 
Example 22
Project: aetros-cli   Author: aetros   File: PredictCommand.py    (license) View Source Project 6 votes vote down vote up
def main(self, args):

        from aetros.predict import predict
        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' predict')
        parser.add_argument('id', nargs='?', help='the job id, e.g. peter/mnist/5d0f81d3ea73e8b2da3236c93f502339190c7037')
        parser.add_argument('--weights', help="Weights path. Per default we try to find it in the ./weights/ folder.")
        parser.add_argument('-i', nargs='+', help="Input (path or url). Multiple allowed")
        parser.add_argument('--th', action='store_true', help="Uses Theano instead of Tensorflow")

        parsed_args = parser.parse_args(args)

        if not parsed_args.id:
            parser.print_help()
            sys.exit()

        if not parsed_args.i:
            parser.print_help()
            sys.exit()

        os.environ['KERAS_BACKEND'] = 'theano' if parsed_args.th else 'tensorflow'
        predict(self.logger, parsed_args.id, parsed_args.i, parsed_args.weights) 
Example 23
Project: aetros-cli   Author: aetros   File: PredictionServerCommand.py    (license) View Source Project 6 votes vote down vote up
def main(self, args):
        import aetros.const

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' server')
        parser.add_argument('id', nargs='?', help='job id')
        parser.add_argument('--weights', help="Weights path. Per default we try to find it in the ./weights/ folder or download it.")
        parser.add_argument('--latest', action="store_true", help="Instead of best epoch we upload latest weights.")
        parser.add_argument('--tf', action='store_true', help="Uses TensorFlow instead of Theano")
        parser.add_argument('--port', help="Changes port. Default 8000")
        parser.add_argument('--host', help="Changes host. Default 127.0.0.1")

        parsed_args = parser.parse_args(args)
        self.lock = Lock()

        sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

        if not parsed_args.id:
            parser.print_help()
            sys.exit()

        os.environ['KERAS_BACKEND'] = 'tensorflow' if parsed_args.tf else 'theano'

        self.model = self.start_model(parsed_args)
        self.start_webserver('127.0.0.1' if not parsed_args.host else parsed_args.host, 8000 if not parsed_args.port else int(parsed_args.port)) 
Example 24
Project: aetros-cli   Author: aetros   File: IdCommand.py    (license) View Source Project 6 votes vote down vote up
def main(self, args):
        import aetros.const

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
                                         prog=aetros.const.__prog__ + ' run')

        parsed_args = parser.parse_args(args)

        user = api.user()

        print("Key installed of account %s (%s)" % (user['username'], user['name']))

        if len(user['accounts']) > 0:
            for orga in six.itervalues(user['accounts']):
                print("  %s of organisation %s (%s)." % ("Owner" if orga['memberType'] == 1 else "Member", orga['username'], orga['name']))
        else:
            print("  Without membership to an organisation.") 
Example 25
Project: actsys   Author: intel-ctrlsys   File: datastore_cli.py    (license) View Source Project 6 votes vote down vote up
def add_log_args(self):
        """
        Add arguments for log manipulations
        :return:
        """
        self.log_parser = self.subparsers.add_parser('log', help="Manipulations for logs",
                                                     formatter_class=argparse.RawTextHelpFormatter)
        self.log_parser.add_argument('action', choices=['list', 'get'])
        # To get multiline help msgs:
        # http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-in-the-help-text
        self.log_parser.add_argument('--limit', '-l', type=int, default=100, required=False)
        self.log_parser.add_argument('--device_list', '-n', type=str, required=False)
        self.log_parser.add_argument('--begin', '-b', required=False)
        self.log_parser.add_argument('--end', '-e', required=False)

        # self.log_parser.add_argument('options', nargs='*', help='''key=value pairs used to assist in selecting
        # and setting attributes
        # More
        # ... and more
        # ...and more!''')
        self.log_parser.set_defaults(func=self.log_execute) 
Example 26
Project: igmonplugins   Author: innogames   File: check_mysql_conf.py    (license) View Source Project 6 votes vote down vote up
def parse_args():
    parser = ArgumentParser(
        formatter_class=RawTextHelpFormatter, description=__doc__
    )
    parser.add_argument(
        '--exe',
        default='/usr/bin/pt-config-diff',
        help='"pt-config-diff" executable (default: %(default)s)',
    )
    parser.add_argument(
        '--host',
        default='localhost',
        help='Target MySQL server (default: %(default)s)',
    )
    parser.add_argument(
        '--user',
        help='MySQL user (default: %(default)s)'
    )
    parser.add_argument(
        '--passwd',
        help='MySQL password (default: %(default)s)'
    )
    parser.add_argument('conf_files', nargs='+')

    return parser.parse_args() 
Example 27
Project: punydomaincheck   Author: anilyuk   File: punydomaincheck.py    (license) View Source Project 6 votes vote down vote up
def arg_parser():
    parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
    parser.add_argument("-u", "--update", action="store_true", default=False, help="Update character set")
    parser.add_argument("--debug", action="store_true", default=False, help="Enable debug logging")
    parser.add_argument("-d", "--domain", default=None, help="Domain without prefix and suffix. (google)")
    parser.add_argument("-s", "--suffix", default=None, help="Suffix to check alternative domain names. (.com, .net)")
    parser.add_argument("-c", "--count", default=1, help="Character count to change with punycode alternative (Default: 1)")
    parser.add_argument("-os", "--original_suffix", default=None,
                        help="Original domain to check for phisihing\n"
                        "Optional, use it with original port to run phishing test")
    parser.add_argument("-op", "--original_port", default=None, help="Original port to check for phisihing\n"
                                                                   "Optional, use it with original suffix to run phishing test")
    parser.add_argument("-f", "--force", action="store_true", default=False,
                        help="Force to calculate alternative domain names")
    parser.add_argument("-t", "--thread", default=15, help="Thread count")

    return parser.parse_args() 
Example 28
Project: helios-sdk-python   Author: harris-helios   File: examples.py    (license) View Source Project 6 votes vote down vote up
def main():
    """Run example queries."""
    parser = argparse.ArgumentParser(
        description='Wrapper for Annotation Detection.',
        formatter_class=argparse.RawTextHelpFormatter)
    required = parser.add_argument_group('Required arguments:')
    required.add_argument('-o',
                          help='Output directory for test results.',
                          required=True,
                          type=str)
    args = parser.parse_args()

    print('Alerts testing...')
    test_alerts(args.o)
    print('Cameras testing...')
    test_cameras(args.o)
    print('Observations testing...')
    test_observations(args.o)
    print('Collections testing...')
    test_collections(args.o)
    print('COMPLETE') 
Example 29
Project: flows   Author: mastro35   File: FlowsManager.py    (license) View Source Project 6 votes vote down vote up
def _parse_input_parameters(self):
        """
        Set the configuration for the Logger
        """
        Global.LOGGER.debug("define and parsing command line arguments")
        parser = argparse.ArgumentParser(
            description='A workflow engine for Pythonistas', formatter_class=argparse.RawTextHelpFormatter)
        parser.add_argument('FILENAME', nargs='+',help='name of the recipe file(s)')
        parser.add_argument('-i', '--INTERVAL', type=int, default=500,
                            metavar=('MS'),
                            help='perform a cycle each [MS] milliseconds. (default = 500)')

        parser.add_argument('-m', '--MESSAGEINTERVAL', type=int, 
                            metavar=('X'),
                            help='dequeue a message each [X] tenth of milliseconds. (default = auto)')
        parser.add_argument('-s', '--STATS', type=int, default=0,
                            metavar=('SEC'),
                            help='show stats each [SEC] seconds. (default = NO STATS)')
        parser.add_argument('-t', '--TRACE', action='store_true',help='enable super verbose output, only useful for tracing')                            
        parser.add_argument('-v', '--VERBOSE', action='store_true',help='enable verbose output')
        parser.add_argument('-V', '--VERSION',
                            action="version", version=__version__)

        args = parser.parse_args()
        return args 
Example 30
Project: JBOPS   Author: blacktwin   File: plays_by_library.py    (license) View Source Project 6 votes vote down vote up
def main():

    lib_lst = [section['section_name'] for section in get_libraries_table()]

    parser = argparse.ArgumentParser(description="Use PlexPy to pull plays by library",
                                     formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-l', '--libraries', nargs='+', type=str, choices=lib_lst, metavar='',
                        help='Space separated list of case sensitive names to process. Allowed names are: \n'
                             '(choices: %(choices)s)')

    opts = parser.parse_args()

    for section in get_libraries_table(opts.libraries):
        sec_name = section['section_name']
        sec_plays = section['plays']
        print(OUTPUT.format(section=sec_name, plays=sec_plays)) 
Example 31
Project: brutespray   Author: x90skysn3k   File: brutespray.py    (license) View Source Project 6 votes vote down vote up
def parse_args():
    
    parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description=\
 
    "Usage: python brutespray.py <OPTIONS> \n")

    menu_group = parser.add_argument_group(colors.lightblue + 'Menu Options' + colors.normal)
    
    menu_group.add_argument('-f', '--file', help="GNMAP or XML file to parse", required=True)
    menu_group.add_argument('-o', '--output', help="Directory containing successful attempts", default="brutespray-output")
    menu_group.add_argument('-s', '--service', help="specify service to attack", default="all")
    menu_group.add_argument('-t', '--threads', help="number of medusa threads", default="2")
    menu_group.add_argument('-T', '--hosts', help="number of hosts to test concurrently", default="1")
    menu_group.add_argument('-U', '--userlist', help="reference a custom username file", default=None)
    menu_group.add_argument('-P', '--passlist', help="reference a custom password file", default=None)
    menu_group.add_argument('-u', '--username', help="specify a single username", default=None)
    menu_group.add_argument('-p', '--password', help="specify a single password", default=None)
    menu_group.add_argument('-c', '--continuous', help="keep brute-forcing after success", default=False, action='store_true')
    menu_group.add_argument('-i', '--interactive', help="interactive mode", default=False, action='store_true')    

    argcomplete.autocomplete(parser)    
    args = parser.parse_args()
    
    return args 
Example 32
Project: BioTaxIDMapper   Author: mkorycinski   File: mapper.py    (license) View Source Project 6 votes vote down vote up
def parse_arguments(argv):
    """Parses user arguments."""

    parser = argparse.ArgumentParser(description=usage,
                                formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-i',
                        '--input-file',
                        help='Input file with FASTA-like deflines',
                        type=str,
                        required=True)
    parser.add_argument('-o',
                        '--output-file',
                        help='Output file with taxonomies marked. ' +
                             'If not specified results will be written to' +
                             '\'annotated.txt\'',
                        type=str,
                        required=False,
                        default='annotated.txt')

    args = parser.parse_args(argv)

    return args 
Example 33
Project: V1D0m   Author: n4xh4ck5   File: v1d0m.py    (license) View Source Project 6 votes vote down vote up
def main (argv):
	parser = argparse.ArgumentParser(description='This script obtains subdomains throught VirusTotal', formatter_class=RawTextHelpFormatter)
	parser.add_argument('-e','--export', help="Export the results to a json file (Y/N)\n Format available:\n\t1.json\n\t2.xlsx", required=False)
	parser.add_argument('-d','--domain', help="The domain to search subdomains",required=True)
	args = parser.parse_args()
	banner()
	help()
	target = args.domain
	output=args.export
	export = ""
	if output is None:
		export='N'
	if ((output == 'y') or (output == 'Y')):
		print "Select the output format:"
		print "\n\t(js).json"
		print "\n\t(xl).xlsx"
		export = raw_input()
		if ((export != "js") and (export != "xl")):
			print "Incorrect output format selected."
			exit(1)
	SendRequest(target,export) 
Example 34
Project: xxNet   Author: drzorm   File: cli.py    (license) View Source Project 6 votes vote down vote up
def parse_argument(argv=None):
    parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
    parser.set_defaults(body=None, headers={})
    make_positional_argument(parser)
    make_troubleshooting_argument(parser)
    args = parser.parse_args(sys.argv[1:] if argv is None else argv)

    if args.debug:
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        log.addHandler(handler)
        log.setLevel(logging.DEBUG)

    set_url_info(args)
    set_request_data(args)
    return args 
Example 35
Project: DBpedia2vec   Author: nausheenfatma   File: dbpedia2vec.py    (license) View Source Project 6 votes vote down vote up
def main():
  parser = argparse.ArgumentParser(prog="DBpedia2vec", 
                                    description="DBpedia2vec embeddings training using Wikipedia dump",
                                    formatter_class=argparse.RawTextHelpFormatter)
  parser.add_argument('--i', metavar='wikipedia xml input file', dest="INFILE", type=str, default=sys.stdin, help="<input-file>", required=True,)
  args = parser.parse_args()

  
  #STEP 1 : parsing wiki documents from xml
  a=WikiXmlHandler()
  a.parse(args.INFILE)
  print "Step 1 complete"
  
  #STEP 2 : reading wkidocuments and joining the page link tokens with underscore into a single token
  x=PagesToSentences()
  x.processWikiPagesData(a.pages_file)
  print "Step 2 complete"
  
  #STEP 3 : word2vec training of sentences
  w2v=Word2VecTraining()
  w2v.train(x.sentencefilename,"../output/model","../output/vocab.txt")  
  print "Step 3 complete. Check output folder!!" 
Example 36
Project: aegea   Author: kislyuk   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def initialize():
    global config, parser
    from .util.printing import BOLD, RED, ENDC
    config = AegeaConfig(__name__, use_yaml=True, save_on_exit=False)
    if not os.path.exists(config.config_files[2]):
        config_dir = os.path.dirname(os.path.abspath(config.config_files[2]))
        try:
            os.makedirs(config_dir)
        except OSError as e:
            if not (e.errno == errno.EEXIST and os.path.isdir(config_dir)):
                raise
        shutil.copy(os.path.join(os.path.dirname(__file__), "user_config.yml"), config.config_files[2])
        logger.info("Wrote new config file %s with default values", config.config_files[2])
        config = AegeaConfig(__name__, use_yaml=True, save_on_exit=False)

    parser = argparse.ArgumentParser(
        description="{}: {}".format(BOLD() + RED() + __name__.capitalize() + ENDC(), fill(__doc__.strip())),
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument("--version", action="version", version="%(prog)s {version}".format(version=__version__))

    def help(args):
        parser.print_help()
    register_parser(help) 
Example 37
Project: os-services   Author: open-power-ref-design-toolkit   File: validate_config.py    (license) View Source Project 6 votes vote down vote up
def main():

    parser = argparse.ArgumentParser(
        description=('Validate the config or inventory yaml file for '
                     'reference architectures.'),
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('--file',
                        dest='file',
                        required=True,
                        help='The path to the config or inventory file.')

    # Handle error cases before attempting to parse
    # a command off the command line
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)
    args = parser.parse_args()
    validate(args.file) 
Example 38
Project: securityonion-airgap   Author: SkiTheSlicer   File: securityonion_airgap_download.py    (license) View Source Project 6 votes vote down vote up
def parse_arguments():
  from datetime import datetime
  import argparse
  import os
  datetime_now = datetime.now().strftime('%Y%m%d-%H%M')
  parser = argparse.ArgumentParser(
    prog='securityonion_airgap_download.py',
    description='Download updates for tools within Security Onion.',
    epilog='Created by SkiTheSlicer (https://github.com/SkiTheSlicer)')
    #formatter_class=argparse.RawTextHelpFormatter)
  parser.add_argument('-e', '--snort-email',
                      nargs='?',
                      help='If supplied, download VRT Registered Rulesets with specified snort.org email address.')#,
                      #action='store_true')
  parser.add_argument('-d', '--output-dir',
                      nargs='?', default="so-airgap-"+datetime_now,
                      help='If supplied, download files to specific directory.')#,
                      #action='store_true')
  return parser.parse_args() 
Example 39
Project: hdidx-eval   Author: hdidx   File: eval_indexer.py    (license) View Source Project 6 votes vote down vote up
def getargs():
    """ Parse program arguments.
    """

    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('dataset', type=str,
                        help='path of the dataset')
    parser.add_argument('--exp_dir', type=str,
                        help='directory for saving experimental results')
    parser.add_argument("--nbits", type=int, nargs='+', default=[64],
                        help="number of bits")
    parser.add_argument("--topk", type=int, default=100,
                        help="retrieval `topk` nearest neighbors")
    parser.add_argument("--coarsek", type=int, default=1024,
                        help="size of the coarse codebook for IVFPQ")
    parser.add_argument("--eval_idx", type=int, default=-1,
                        help="index of v_indexer_param, -1 means all")
    parser.add_argument("--log", type=str, default="INFO",
                        help="log level")

    return parser.parse_args() 
Example 40
Project: hdidx-eval   Author: hdidx   File: eval_annoy.py    (license) View Source Project 6 votes vote down vote up
def getargs():
    """ Parse program arguments.
    """

    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('dataset', type=str,
                        help='path of the dataset')
    parser.add_argument('--exp_dir', type=str,
                        help='directory for saving experimental results')
    parser.add_argument("--ntrees", type=int, nargs='+', default=[16],
                        help="number of trees")
    parser.add_argument("--topk", type=int, default=100,
                        help="retrieval `topk` nearest neighbors")
    parser.add_argument("--log", type=str, default="INFO",
                        help="log level")

    return parser.parse_args() 
Example 41
Project: hdidx-eval   Author: hdidx   File: eval_nearpy.py    (license) View Source Project 6 votes vote down vote up
def getargs():
    """ Parse program arguments.
    """

    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('dataset', type=str,
                        help='path of the dataset')
    parser.add_argument('--exp_dir', type=str,
                        help='directory for saving experimental results')
    parser.add_argument("--nbits", type=int, nargs='+', default=[32, 16, 8],
                        help="number of bits per hash tables")
    parser.add_argument("--ntbls", type=int, nargs='+', default=[2, 4, 8],
                        help="number of hash tables")
    parser.add_argument("--topk", type=int, default=100,
                        help="retrieval `topk` nearest neighbors")
    parser.add_argument("--log", type=str, default="INFO",
                        help="log level")

    return parser.parse_args() 
Example 42
Project: hdidx-eval   Author: hdidx   File: plot_report.py    (license) View Source Project 6 votes vote down vote up
def getargs():
    """ Parse program arguments.
    """

    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('report', type=str,
                        help='report file')
    parser.add_argument('figdir', type=str,
                        help='directory to save the figure ')
    parser.add_argument('indexers', type=str, nargs='+',
                        help='(PQIndexer|SHIndexer)')
    parser.add_argument("--log", type=str, default="INFO",
                        help="log level")

    return parser.parse_args() 
Example 43
Project: MMM-GoogleAssistant   Author: gauravsacc   File: assistant.py    (license) View Source Project 6 votes vote down vote up
def init_googleAssistant():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--credentials', type=existing_file,
                        metavar='OAUTH2_CREDENTIALS_FILE',
                        default=os.path.join(
                            os.path.expanduser('/home/pi/.config'),
                            'google-oauthlib-tool',
                            'credentials.json'
                        ),
                        help='Path to store and read OAuth2 credentials')
    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))

    with Assistant(credentials) as assistant:
        for event in assistant.start():
            process_event(event) 
Example 44
Project: ultra_ping   Author: mrahtz   File: common.py    (license) View Source Project 6 votes vote down vote up
def parse_args(description):
    """
    Parse arguments.
    """

    parser = argparse.ArgumentParser(
        description=description, formatter_class=argparse.RawTextHelpFormatter)
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--server', action='store_true')
    group.add_argument('--client')
    parser.add_argument("--n_packets", type=int, default=100)
    parser.add_argument("--payload_len", type=int, default=256)
    parser.add_argument("--send_rate_kBps", type=int, default=400)
    parser.add_argument(
        "--output_filename", default='udp_packetn_latency_pairs')
    parser.add_argument("--listen_port", type=int, default=8888)
    args = parser.parse_args()
    return args 
Example 45
Project: Codex   Author: TomCrypto   File: codex.py    (license) View Source Project 6 votes vote down vote up
def cli_classify():
    parser = argparse.ArgumentParser(description=_classify_descr,
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('dataset', nargs=1, metavar='DATASET',
                        help="path to pre-trained dataset")
    parser.add_argument('files', nargs='*', metavar='FILE',
                        help="paths to files to classify")

    args = parser.parse_args()

    classifier = Classifier(args.dataset[0])

    if not args.files:
        args.files = ['-']

    for path in args.files:
        if path == '-':
            text = ''.join(sys.stdin.readlines())
        else:
            with open(path, 'r', encoding='utf-8', errors='ignore') as f:
                text = ''.join(f.readlines())

        print('{0}\t{1}'.format(path, classifier.classify(text))) 
Example 46
Project: PyGPS   Author: ymcmrs   File: diff_gps_space.py    (license) View Source Project 6 votes vote down vote up
def cmdLineParse():
    parser = argparse.ArgumentParser(description='Download GPS data over SAR coverage.',\
                                     formatter_class=argparse.RawTextHelpFormatter,\
                                     epilog=INTRODUCTION+'\n'+EXAMPLE)

    parser.add_argument('RefDate',help='Reference date of differential InSAR')
    parser.add_argument('-d', dest = 'date', help='date for estimation.')
    parser.add_argument('--datetxt', dest = 'datetxt', help='text file of date.')
    parser.add_argument('--Atm',action="store_true", default=False, help='Geting SAR LOS tropospheric delay.')
    parser.add_argument('--Def', action="store_true", default=False, help='Getting SAR LOS deformation.')
    
    inps = parser.parse_args()
    
    if not inps.date and not inps.datetxt:
        parser.print_usage()
        sys.exit(os.path.basename(sys.argv[0])+': error: date and date_txt File, at least one is needed.')

    return inps

    
#################################################################################################### 
Example 47
Project: PyGPS   Author: ymcmrs   File: plot_gps_insar.py    (license) View Source Project 6 votes vote down vote up
def cmdLineParse():
    parser = argparse.ArgumentParser(description='Download GPS data over SAR coverage.',\
                                     formatter_class=argparse.RawTextHelpFormatter,\
                                     epilog=INTRODUCTION+'\n'+EXAMPLE)

    parser.add_argument('FILE',help='2D file that need to be plotted.')
    parser.add_argument('WIDTH', help='width of the 2D file. i.e., range columns for RDC, longitude conlumns for GEC.')
    parser.add_argument('-d','--dem', dest='dem', help='background DEM that used to show the background terrain.')
    parser.add_argument('-t', dest='txt', help='information of gps stations tesxt whose columns should obey: Name, lat, lon, range, azimuth')
    parser.add_argument('-m','--mask',dest='mask',  help='Masking the image with mask file.')
    
    inps = parser.parse_args()

    return inps

################################################################################################ 
Example 48
Project: PyGPS   Author: ymcmrs   File: diff_gps_space_all.py    (license) View Source Project 6 votes vote down vote up
def cmdLineParse():
    parser = argparse.ArgumentParser(description='Download GPS data over SAR coverage.',\
                                     formatter_class=argparse.RawTextHelpFormatter,\
                                     epilog=INTRODUCTION+'\n'+EXAMPLE)

    parser.add_argument('projectName',help='Name of project.')
    parser.add_argument('--Atm',action="store_true", default=False, help='Geting SAR LOS tropospheric delay.')
    parser.add_argument('--Def', action="store_true", default=False, help='Getting SAR LOS deformation.')
    
    inps = parser.parse_args()


    return inps

    
#################################################################################################### 
Example 49
Project: PyGPS   Author: ymcmrs   File: gps_coord_trans.py    (license) View Source Project 6 votes vote down vote up
def cmdLineParse():
    parser = argparse.ArgumentParser(description='Transforming GPS coordinates into radar coordinates.',\
                                     formatter_class=argparse.RawTextHelpFormatter,\
                                     epilog=INTRODUCTION+'\n'+EXAMPLE)

    parser.add_argument('gps_txt',help='Available GPS station information.')
    parser.add_argument('-l', dest='lt', help='lookup table of coordinates transfomration.')
    parser.add_argument('-p', dest='dem_par', help='Parameter file of lookup table.')
    parser.add_argument('-o', dest='out', help='Output file name of the generated GPS coordinates text.')
    
    inps = parser.parse_args()
    
    if not inps.lt:
        parser.print_usage()
        sys.exit(os.path.basename(sys.argv[0])+': error: lookup table should be provided.')

    if not inps.dem_par:
        parser.print_usage()
        sys.exit(os.path.basename(sys.argv[0])+': error: dem_par file should be provided.')

    return inps

################################################################################################ 
Example 50
Project: PyGPS   Author: ymcmrs   File: search_gps.py    (license) View Source Project 6 votes vote down vote up
def cmdLineParse():
    parser = argparse.ArgumentParser(description='Download GPS data over SAR coverage.',\
                                     formatter_class=argparse.RawTextHelpFormatter,\
                                     epilog=INTRODUCTION+'\n'+EXAMPLE)

    parser.add_argument('-p', dest = 'projectName',help='Project name of the processing datasets.')
    parser.add_argument('-t', dest='SLCpar', help='One SLC par file of the resaerch region.')
    parser.add_argument('-s', dest='Dbeg', help='Beginning date of available GPS data.')
    parser.add_argument('-e', dest='Dend', help='Ending date of available GPS data.')
    
    inps = parser.parse_args()
    
    if not inps.projectName and not inps.SLCpar:
        parser.print_usage()
        sys.exit(os.path.basename(sys.argv[0])+': error: projectName and SLCpar File, at least one is needed.')
    return inps

    return inps

################################################################################################