Python argparse.RawTextHelpFormatter() Examples

The following are 60 code examples for showing how to use argparse.RawTextHelpFormatter(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

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

Example 1
Project: DNA-GAN   Author: Prinsphield   File: train.py    License: MIT License 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='test', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument(
        '-a', '--attributes',
        nargs='+',
        type=str,
        help='Specify attribute name for training. \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.attributes)
    DNA_GAN = Model(args.attributes, is_train=True)
    run(config, celebA, DNA_GAN, gpu=args.gpu) 
Example 2
Project: toil-scripts   Author: BD2KGenomics   File: transfer_gtex_to_s3.py    License: Apache License 2.0 6 votes vote down vote up
def build_parser():
    parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-s', '--sra', default=None, required=True,
                        help='Path to a file with one analysis ID per line for data hosted on CGHub.')
    parser.add_argument('-k', '--dbgap_key', default=None, required=True,
                        help='Path to a CGHub key that has access to the TCGA data being requested. An exception will'
                             'be thrown if "-g" is set but not this argument.')
    parser.add_argument('--s3_dir', default=None, required=True, help='S3 Bucket. e.g. tcga-data')
    parser.add_argument('--ssec', default=None, required=True, help='Path to Key File for SSE-C Encryption')
    parser.add_argument('--single_end', default=None, action='store_true', help='Set this flag if data is single-end')
    parser.add_argument('--sudo', dest='sudo', default=None, action='store_true',
                        help='Docker usually needs sudo to execute locally, but not when running Mesos or when '
                             'the user is a member of a Docker group.')
    return parser


# Convenience Functions 
Example 3
Project: aetros-cli   Author: aetros   File: PredictCommand.py    License: MIT License 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")

        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'] = 'tensorflow'
        predict(self.logger, parsed_args.id, parsed_args.i, parsed_args.weights) 
Example 4
Project: aetros-cli   Author: aetros   File: IdCommand.py    License: MIT License 6 votes vote down vote up
def main(self, args):
        import aetros.const

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

        parsed_args = parser.parse_args(args)
        config = read_home_config()


        try:
            user = api.user()
        except KeyNotConfiguredException as e:
            self.logger.error(str(e))
            sys.exit(1)

        print("Logged in as %s (%s) on %s" % (user['username'], user['name'], config['host']))

        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 5
Project: aetros-cli   Author: aetros   File: ModelCommand.py    License: MIT License 6 votes vote down vote up
def main(self, args):
        import aetros.const

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

        parsed_args = parser.parse_args(args)

        home_config = read_home_config()
        config_path = find_config_path()

        if not config_path:
            print("No model configuration file (aetros.yml). Switch to a directory first..")
            sys.exit(1)

        config = find_config(error_on_missing=True)
        print("Model %s in %s used in all aetros commands." % (config['model'], os.path.dirname(config_path)))

        git_remote_url = 'git@%s:%s.git' % (home_config['host'], config['model'])
        print("Git url: %s" % (git_remote_url,)) 
Example 6
Project: aetros-cli   Author: aetros   File: GPUCommand.py    License: MIT License 6 votes vote down vote up
def main(self, args):
        import aetros.cuda_gpu

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

        try:
            print("CUDA version: " +str(aetros.cuda_gpu.get_version()))
        except aetros.cuda_gpu.CudaNotImplementedException:
            sys.stderr.write('It seems you dont have NVIDIA CUDA not installed properly.')
            sys.exit(2)

        for gpu in aetros.cuda_gpu.get_ordered_devices():
            properties = aetros.cuda_gpu.get_device_properties(gpu['device'], all=True)
            free, total = aetros.cuda_gpu.get_memory(gpu['device'])
            print("%s GPU id=%s %s (memory %.2fGB, free %.2fGB)" %(gpu['fullId'], str(gpu['id']), properties['name'], total/1024/1024/1024, free/1024/1024/1024)) 
Example 7
Project: BerePi   Author: jeonghoonkang   File: save_list_2_excel.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def parse_args():
    story = u"파일명, 데이터 시작셀과 마지막셀 입력"
    usg = u'\n python save_list.py -fname "sample" -s T4 -e T38'
    parser = argparse.ArgumentParser(description=story, usage=usg, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-f", default="sample", help=u"파일명, e.g.) sample")
    parser.add_argument("-s", default='T4', help=u"데이터 시작 셀, e.g.) T4")
    parser.add_argument("-e", default='T38', help=u"데이터 마지막 셀, e.g.) T38")
    parser.add_argument("-n", default='test.py', help=u"생성할 파일명, e.g) test.py")
    args = parser.parse_args()

    # check
    f = args.f
    s = args.s
    e = args.e
    n = args.n
    return f, s, e, n 
Example 8
Project: BerePi   Author: jeonghoonkang   File: save_excel_2_list.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def parse_args():
    story = u"파일명, 데이터 시작셀과 마지막셀 입력"
    usg = u'\n python save_list.py -f "sample" -t 0 -s T4 -e T38'
    parser = argparse.ArgumentParser(description=story, usage=usg, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-f", default="2017-07-24 17.12.00_new_ee_with_DB", help=u"파일명")
    parser.add_argument("-t", default="0", help=u"Sheet Tab: 0, 1, 2 ...")
    parser.add_argument("-s", default='G2', help=u"데이터 시작 셀")
    parser.add_argument("-e", default='G746', help=u"데이터 마지막 셀")
    args = parser.parse_args()

    # check
    f = args.f
    t = args.t
    s = args.s
    e = args.e
    return f, t, s, e 
Example 9
Project: MMM-GoogleAssistant   Author: gauravsacc   File: assistant.py    License: MIT License 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,"magic-mirror-device-id") as assistant:
        for event in assistant.start():
            process_event(event) 
Example 10
Project: 3gpp-citations   Author: martisak   File: standardcitations.py    License: MIT License 6 votes vote down vote up
def parse_args(args):
    """
    Parse arguments
    """

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

    parser.add_argument('--input', '-i', metavar='INPUT',
                        required=True,
                        help=('The Excel file generated by and '
                              'exported from the 3GPP Portal '
                              '(https://portal.3gpp.org)'))
    parser.add_argument('--output', '-o', metavar='OUTPUT',
                        help=('The bib file to write to. '
                              'STDOUT is used if omitted.'))
    parser.add_argument('--xelatex',
                        action='store_true',
                        help='Use line breaks')

    args = parser.parse_args(args)

    return args 
Example 11
Project: grimoire   Author: RUB-SysSec   File: config.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __load_arguments(self):
        modes = ["m32", "m64"]
        modes_help = 'm32\tpack and compile as an i386   executable.\n' \
                     'm64\tpack and compile as an x86-64 executable.\n'

        parser = ArgsParser(formatter_class=argparse.RawTextHelpFormatter)

        parser.add_argument('binary_file', metavar='<Executable>', action=FullPath, type=parse_is_file,
                            help='path to the user space executable file.')
        parser.add_argument('output_dir', metavar='<Output Directory>', action=FullPath, type=parse_is_dir,
                            help='path to the output directory.')
        parser.add_argument('mode', metavar='<Mode>', choices=modes, help=modes_help)
        parser.add_argument('-args', metavar='<args>', help='define target arguments.', default="", type=str)
        parser.add_argument('-file', metavar='<file>', help='write payload to file instead of stdin.', default="",
                            type=str)
        parser.add_argument('--recompile', help='recompile all agents.', action='store_true', default=False)
        parser.add_argument('-m', metavar='<memlimit>', help='set memory limit [MB] (default 50 MB).', default=50,
                            type=int)
        parser.add_argument('--asan', help='disables memlimit (required for ASAN binaries)', action='store_true', default=False)

        self.argument_values = vars(parser.parse_args()) 
Example 12
Project: upload-scripts   Author: openstreetcam   File: osc_tools.py    License: MIT License 6 votes vote down vote up
def add_upload_parser(subparsers: ArgumentParser):
    """Adds upload parser"""
    upload_parser = subparsers.add_parser('upload', formatter_class=RawTextHelpFormatter)
    upload_parser.set_defaults(func=upload_command)
    upload_parser.add_argument('-p',
                               '--path',
                               required=True,
                               help='Full path directory that contains sequence(s) '
                                    'folder(s) to upload')
    upload_parser.add_argument('-w',
                               '--workers',
                               required=False,
                               type=int,
                               default=10,
                               choices=range(1, 21),
                               metavar="[1-20]",
                               help='Number of parallel workers used to upload files. '
                                    'Default number is 10.')
    _add_environment_argument(upload_parser)
    _add_logging_argument(upload_parser) 
Example 13
Project: UnifiedMessageRelay   Author: JQ-Networks   File: daemon.py    License: MIT License 6 votes vote down vote up
def main():
    # ARGS
    argP = argparse.ArgumentParser(
        description="QQ <-> Telegram Bot Framework & Forwarder", formatter_class=argparse.RawTextHelpFormatter)
    cmdHelpStr = """
start   - start bot as a daemon
stop    - stop bot
restart - restart bot
run     - run as foreground Debug mode. every log will print to screen and log to file.
"""
    argP.add_argument("command", type=str, action="store",
                      choices=['start', 'stop', 'restart', 'run'], help=cmdHelpStr)
    daemon = MainProcess('/tmp/coolq-telegram-bot.pid')
    args = argP.parse_args()
    if args.command == 'start':
        daemon.start(debug_mode=True)
    elif args.command == 'stop':
        daemon.stop()
    elif args.command == 'restart':
        daemon.restart(debug_mode=True)
    elif args.command == 'run':
        # Run as foreground mode
        daemon.run(debug_mode=True) 
Example 14
Project: dax   Author: VUIIS   File: xnat_tools_utils.py    License: MIT License 6 votes vote down vote up
def parse_args(name, description, add_tools_arguments, purpose,
               extra_display=''):
    """
    Method to parse arguments base on argparse

    :param name: name of the script
    :param description: description of the script for help display
    :param add_tools_arguments: fct to add arguments to parser
    :param purpose: purpose of the script
    :param extra_display: extra display
    :return: parser object
    """
    from argparse import ArgumentParser, RawTextHelpFormatter
    parser = ArgumentParser(prog=name, description=description,
                            formatter_class=RawTextHelpFormatter)
    parser.add_argument('--host', dest='host', default=None,
                        help='Host for XNAT. Default: env XNAT_HOST.')
    parser.add_argument('-u', '--username', dest='username', default=None,
                        help='Username for XNAT.')
    parser = add_tools_arguments(parser)
    main_display(name, purpose, extra_display)
    args = parser.parse_args()
    args_display(args)
    return args 
Example 15
Project: skelebot   Author: carsdotcom   File: skeleParser.py    License: MIT License 5 votes vote down vote up
def __init__(self, config=None, env=None):
        """Initialize the argparse Parser based on the Config data if it is present"""

        self.config = config
        self.env = env
        self.desc = self.buildDescription()

        # ---Standard Parser Setup---

        # Construct the root argument parser from which all sub-parsers will be built
        formatter = argparse.RawTextHelpFormatter
        self.parser = argparse.ArgumentParser(description=self.desc, formatter_class=formatter)
        self.parser.add_argument(VN_ALT, VN_ARG, help=VN_HELP, action='store_true', dest=VN_DST)
        subparsers = self.parser.add_subparsers(dest="job")

        if (config.name is None):
            # Add SCF parser
            scaffoldParser = subparsers.add_parser(SCF_ARG, help=SCF_HELP)
            scaffoldParser.add_argument(SCF_EX_ALT, SCF_EX, action='store_true', help=SCF_EX_HELP)
        else:
            # Add STANDARD PARAMS
            self.parser.add_argument(ENV_ALT, ENV_ARG, help=ENV_HELP)
            self.parser.add_argument(SB_ALT, SB_ARG, help=SB_HELP, action='store_true', dest=SB_DST)
            self.parser.add_argument(NT_ALT, NT_ARG, help=NT_HELP, action='store_true', dest=NT_DST)
            self.parser.add_argument(CN_ALT, CN_ARG, help=CN_HELP, action='store_true', dest=CN_DST)

        # ---Config Based Parser Setup---

        # Add JOBS
        if (config.jobs is not None):
            for job in config.jobs:
                subparser = subparsers.add_parser(job.name, help=job.help + " ("+job.source+")")

                # Add ARGS and PARAMS
                subparser = addArgs(job.args, subparser)
                subparser = addParams(job.params, subparser)
                subparser = addParams(config.params, subparser)

        # Add COMPONENT parsers
        for component in self.config.components:
            subparsers = component.addParsers(subparsers) 
Example 16
Project: skelebot   Author: carsdotcom   File: test_components_jupyter.py    License: MIT License 5 votes vote down vote up
def test_addParsers(self):
        jupyter = sb.components.jupyter.Jupyter(port=1127, folder="notebooks/")

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers(dest="job")
        subparsers = jupyter.addParsers(subparsers)

        self.assertNotEqual(subparsers.choices["jupyter"], None) 
Example 17
Project: skelebot   Author: carsdotcom   File: test_components_plugin.py    License: MIT License 5 votes vote down vote up
def test_addParsers(self):
        plugin = sb.components.plugin.Plugin()

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers(dest="job")
        subparsers = plugin.addParsers(subparsers)

        self.assertNotEqual(subparsers.choices["plugin"], None) 
Example 18
Project: skelebot   Author: carsdotcom   File: test_components_artifactory.py    License: MIT License 5 votes vote down vote up
def test_addParsers(self):
        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers(dest="job")
        subparsers = self.artifactory.addParsers(subparsers)

        self.assertNotEqual(subparsers.choices["push"], None)
        self.assertNotEqual(subparsers.choices["pull"], None) 
Example 19
Project: skelebot   Author: carsdotcom   File: test_components_repository_repository.py    License: MIT License 5 votes vote down vote up
def test_addParsers_artifactory(self):
        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers(dest="job")
        subparsers = self.artifactory.addParsers(subparsers)

        self.assertNotEqual(subparsers.choices["push"], None)
        self.assertNotEqual(subparsers.choices["pull"], None) 
Example 20
Project: skelebot   Author: carsdotcom   File: test_components_bump.py    License: MIT License 5 votes vote down vote up
def test_addParsers(self):
        bump = sb.components.bump.Bump()

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers(dest="job")
        subparsers = bump.addParsers(subparsers)

        self.assertNotEqual(subparsers.choices["bump"], None) 
Example 21
Project: skelebot   Author: carsdotcom   File: test_components_dexec.py    License: MIT License 5 votes vote down vote up
def test_addParsers(self):
        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers(dest="job")
        dexec = sb.components.dexec.Dexec()
        subparsers = dexec.addParsers(subparsers)

        self.assertNotEqual(subparsers.choices["exec"], None) 
Example 22
Project: skelebot   Author: carsdotcom   File: test_components_registry.py    License: MIT License 5 votes vote down vote up
def test_addParsers(self):
        registry = sb.components.registry.Registry(host="docker.io", port=88, user="skelebot")

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers(dest="job")
        subparsers = registry.addParsers(subparsers)

        self.assertNotEqual(subparsers.choices["publish"], None) 
Example 23
Project: skelebot   Author: carsdotcom   File: test_components_prime.py    License: MIT License 5 votes vote down vote up
def test_addParsers(self):
        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers(dest="prime")
        prime = sb.components.prime.Prime()
        subparsers = prime.addParsers(subparsers)

        self.assertNotEqual(subparsers.choices["prime"], None) 
Example 24
Project: raspiblitz   Author: rootzoll   File: main.py    License: MIT License 5 votes vote down vote up
def main():
    # make sure CTRL+C works
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    description = """BlitzTUI - the Touch-User-Interface for the RaspiBlitz project

Keep on stacking SATs..! :-D"""

    parser = argparse.ArgumentParser(description=description, formatter_class=RawTextHelpFormatter)
    parser.add_argument("-V", "--version",
                        help="print version", action="version",
                        version=__version__)

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

    # parse args
    args = parser.parse_args()

    if args.debug:
        setup_logging(log_level="DEBUG")
    else:
        setup_logging()

    log.info("Starting BlitzTUI v{}".format(__version__))

    # initialize app
    app = QApplication(sys.argv)

    w = AppWindow()
    w.show()

    # run app
    sys.exit(app.exec_()) 
Example 25
Project: qutebrowser   Author: qutebrowser   File: hist_importer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parse():
    """Parse command line arguments."""
    description = ("This program is meant to extract browser history from your"
                   " previous browser and import them into qutebrowser.")
    epilog = ("Databases:\n\n\tqutebrowser: Is named 'history.sqlite' and can "
              "be found at your --basedir. In order to find where your "
              "basedir is you can run ':open qute:version' inside qutebrowser."
              "\n\n\tFirefox: Is named 'places.sqlite', and can be found at "
              "your system's profile folder. Check this link for where it is "
              "located: http://kb.mozillazine.org/Profile_folder"
              "\n\n\tChrome: Is named 'History', and can be found at the "
              "respective User Data Directory. Check this link for where it is"
              "located: https://chromium.googlesource.com/chromium/src/+/"
              "master/docs/user_data_dir.md\n\n"
              "Example: hist_importer.py -b firefox -s /Firefox/Profile/"
              "places.sqlite -d /qutebrowser/data/history.sqlite")
    parser = argparse.ArgumentParser(
        description=description, epilog=epilog,
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument('-b', '--browser', dest='browser', required=True,
                        type=str, help='Browsers: {firefox, chrome}')
    parser.add_argument('-s', '--source', dest='source', required=True,
                        type=str, help='Source: Full path to the sqlite data'
                        'base file from the source browser.')
    parser.add_argument('-d', '--dest', dest='dest', required=True, type=str,
                        help='\nDestination: Full path to the qutebrowser '
                        'sqlite database')
    return parser.parse_args() 
Example 26
Project: ripe-atlas-tools   Author: RIPE-NCC   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _format_usage(self, *args):
        r = argparse.RawTextHelpFormatter._format_usage(
            self, *args).capitalize()
        return "\n\n{}\n".format(r) 
Example 27
Project: DNA-GAN   Author: Prinsphield   File: vis.py    License: MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='test', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-i', '--input', type=str, help='image path')
    parser.add_argument('-a', '--attributes', type=str, nargs='+', help='attribute list')
    parser.add_argument('--model_dir', type=str, default='train_log/model/', help='path to the model')
    parser.add_argument('--latent_path', type=str, default='latent', help='path to the model')
    parser.add_argument('-g', '--gpu', type=str, default='', help='gpu ids')
    args = parser.parse_args()

    os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
    if not os.path.exists(args.latent_path): os.makedirs(args.latent_path)

    DNA_GAN = Model(feature_list=args.attributes, is_train=False, nhwc=[1,64,64,3])
    img = np.expand_dims(misc.imresize(misc.imread(args.input), (DNA_GAN.height, DNA_GAN.width)), axis=0)
    get_representation(img, DNA_GAN, args.model_dir, args.latent_path) 
Example 28
Project: PoseWarper   Author: facebookresearch   File: eval_motchallenge.py    License: Apache License 2.0 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description="""
Compute metrics for trackers using MOTChallenge ground-truth data.

Files
-----
All file content, ground truth and test files, have to comply with the
format described in 

Milan, Anton, et al. 
"Mot16: A benchmark for multi-object tracking." 
arXiv preprint arXiv:1603.00831 (2016).
https://motchallenge.net/

Structure
---------

Layout for ground truth data
    <GT_ROOT>/<SEQUENCE_1>/gt/gt.txt
    <GT_ROOT>/<SEQUENCE_2>/gt/gt.txt
    ...

Layout for test data
    <TEST_ROOT>/<SEQUENCE_1>.txt
    <TEST_ROOT>/<SEQUENCE_2>.txt
    ...

Sequences of ground truth and test will be matched according to the `<SEQUENCE_X>`
string.""", formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('groundtruths', type=str, help='Directory containing ground truth files.')   
    parser.add_argument('tests', type=str, help='Directory containing tracker result files')
    parser.add_argument('--loglevel', type=str, help='Log level', default='info')
    parser.add_argument('--fmt', type=str, help='Data format', default='mot15-2D')
    return parser.parse_args() 
Example 29
Project: toil-scripts   Author: BD2KGenomics   File: transfer_tcga_to_s3.py    License: Apache License 2.0 5 votes vote down vote up
def build_parser():
    parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-g', '--genetorrent', default=None, required=True,
                        help='Path to a file with one analysis ID per line for data hosted on CGHub.')
    parser.add_argument('-k', '--genetorrent_key', default=None, required=True,
                        help='Path to a CGHub key that has access to the TCGA data being requested. An exception will'
                             'be thrown if "-g" is set but not this argument.')
    parser.add_argument('--s3_dir', default=None, required=True, help='S3 Bucket. e.g. tcga-data')
    parser.add_argument('--ssec', default=None, required=True, help='Path to Key File for SSE-C Encryption')
    return parser


# Convenience Functions 
Example 30
Project: dipper   Author: monarch-initiative   File: add-properties2turtle.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(
        description='description',
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument(
        '--input', '-i', type=str, required=True,
        help='Location of input file')

    parser.add_argument(
        '--output', '-o', type=str, required=True,
        help='Location of output file')

    parser.add_argument(
        '--input_format', '-f', type=str, default="turtle",
        help='format of source rdf file (turtle, nt, rdf/xml)')

    parser.add_argument(
        '--output_format', '-g', type=str, default="turtle",
        help='format of target rdf file (turtle, nt, rdf/xml)')

    args = parser.parse_args()
    property_list = get_properties_from_input(args.input, args.input_format)
    merged_graph = make_property_graph(property_list, args)

    # merge graphs
    merged_graph.parse(args.input, format=args.input_format)

    merged_graph.serialize(args.output, format=args.output_format) 
Example 31
Project: SniffVPN   Author: toolsprods   File: SniffVPN.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parse_args():
  parser = argparse.ArgumentParser(description="SniffVPN v{} - '{}'".format(version,codename)+"\nA tool to sniff all HTTP traffic passing through your VPN and analyzer malicious urls",
				   version="SniffVPN v{} - '{}'".format(version, codename),
				   usage='python SniffVPN.py [options]',
				   epilog="The author is not responsible for any misuse of the application",
				   formatter_class=RawTextHelpFormatter)
  #parser.add_argument('-i', dest='interface', type=str, help="Interface to use for sniff, default tun0 for VPN")
  parser.add_argument('--nologs', action='store_false', help="Disable logs")
  return parser.parse_args()

#Function to detect if VPN is installed 
Example 32
Project: wal_steam   Author: kotajacob   File: wal_steam.py    License: MIT License 5 votes vote down vote up
def getArgs():
    # get the arguments with argparse
    description = "Wal Steam"
    arg = argparse.ArgumentParser(description=description, formatter_class=RawTextHelpFormatter)

    arg.add_argument("-v", "--version", action="store_true",
        help="Print wal_steam version.")

    arg.add_argument("-w", action="store_true",
        help="Get colors from wal.")

    arg.add_argument("-g", action="store_true",
        help="Get colors from wpg.")

    arg.add_argument("-s",
        help="Enter a custom steam skin directory.")

    arg.add_argument("-d", action="store_true",
        help="Apply high dpi patches.")

    arg.add_argument("-u", action="store_true",
        help=f"Force update cache, skin, and config file. {CLI_RED}WARNING:{CLI_END} WILL OVERWRITE config.json")

    arg.add_argument("-f", "--fonts",
        help=textwrap.dedent(f'''
            Specify custom fonts. Enter font styles separated by comma.
            {CLI_BOLD}Available styles:{CLI_END} basefont, semibold, semilight, light.
            {CLI_YELLOW}Example:{CLI_END} 'Open Sans, Open Sans Semibold, Open Sans Semilight, Open Sans Light'
            {CLI_RED}WARNING:{CLI_END} Fonts must already be installed on your system.'''))

    arg.add_argument("-a", "--attempts", help="Set the number of patch download attempts (DEFAULT=5)")

    return arg.parse_args() 
Example 33
Project: XSSCon   Author: menkrep1337   File: xsscon.py    License: MIT License 5 votes vote down vote up
def start():
	parse=argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,usage="XSSCon -u <target> [options]",epilog=epilog,add_help=False)
	
	pos_opt=parse.add_argument_group("Options")
	pos_opt.add_argument("--help",action="store_true",default=False,help="Show usage and help parameters")
	pos_opt.add_argument("-u",metavar="",help="Target url (e.g. http://testphp.vulnweb.com)")
	pos_opt.add_argument("--depth",metavar="",help="Depth web page to crawl. Default: 2",default=2)
	pos_opt.add_argument("--payload-level",metavar="",help="Level for payload Generator, 7 for custom payload. {1...6}. Default: 6",default=6)
	pos_opt.add_argument("--payload",metavar="",help="Load custom payload directly (e.g. <script>alert(2005)</script>)",default=None)
	pos_opt.add_argument("--method",metavar="",help="Method setting(s): \n\t0: GET\n\t1: POST\n\t2: GET and POST (default)",default=2,type=int)
	pos_opt.add_argument("--user-agent",metavar="",help="Request user agent (e.g. Chrome/2.1.1/...)",default=agent)
	pos_opt.add_argument("--single",metavar="",help="Single scan. No crawling just one address")
	pos_opt.add_argument("--proxy",default=None,metavar="",help="Set proxy (e.g. {'https':'https://10.10.1.10:1080'})")
	pos_opt.add_argument("--about",action="store_true",help="Print information about XSSCon tool")
	pos_opt.add_argument("--cookie",help="Set cookie (e.g {'ID':'1094200543'})",default='''{"ID":"1094200543"}''',metavar="")
	
	getopt=parse.parse_args()
	print(logo)
	Log.info("Starting XSSCon...")
	if getopt.u:
		core.main(getopt.u,getopt.proxy,getopt.user_agent,check(getopt),getopt.cookie,getopt.method)
		
		crawler.crawl(getopt.u,int(getopt.depth),getopt.proxy,getopt.user_agent,check(getopt),getopt.method,getopt.cookie)
		
	elif getopt.single:
		core.main(getopt.single,getopt.proxy,getopt.user_agent,check(getopt),getopt.cookie,getopt.method)
		
	elif getopt.about:
		print("""
***************
Project: XSSCon
License: MIT
Author: menkrep1337
Last updates: 2019 may 26
Note: Take your own RISK
****************
"""+epilog)
	else:
		parse.print_help() 
Example 34
Project: mysql_utils   Author: pinterest   File: find_shard_mismatches.py    License: GNU General Public License v2.0 5 votes vote down vote up
def main():
    description = ("MySQL orpahned shard detector\n\n"
                   "This utility will attempt to find orphaned databases "
                   "across sharded MySQL systems")

    parser = argparse.ArgumentParser(description=description,
                                     formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-i',
                        '--instance',
                        help='Check a single instance rather than all',
                        default=False)
    args = parser.parse_args()

    if args.instance:
        instance = host_utils.HostAddr(args.instance)
    else:
        instance = False

    orphaned, orphaned_but_used, missing = find_shard_mismatches(instance)

    for o in orphaned:
        log.info('Orphan dbs: {host} {dbs}'.format(
            host=o, dbs=','.join(orphaned[o])))

    for obu in orphaned_but_used:
        log.info('Orphan, but still used, dbs: {host} {dbs}'.format(
            host=obu, dbs=','.join(orphaned_but_used[obu])))

    for m in missing:
        log.info('Missing dbs:{host} {dbs}'.format(
            host=m, dbs=','.join(missing[m])))

    if not (orphaned or orphaned_but_used or missing):
        log.info('No problems found!') 
Example 35
Project: PHEnix   Author: phe-bioinformatics   File: run_snp_pipeline.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_args():
    args = argparse.ArgumentParser(description=get_desc(), formatter_class=RawTextHelpFormatter)

    args.add_argument("--workflow", "-w")
    args.add_argument("--input", "-i")

    args.add_argument("-r1", help="R1/Forward read in Fastq format.")
    args.add_argument("-r2", help="R2/Reverse read in Fastq format.")
    args.add_argument("--reference", "-r", help="Rerefence to use for mapping.")
    args.add_argument("--sample-name", default="test_sample", help="Name of the sample for mapper to include as read groups.")
    args.add_argument("--outdir", "-o")

    args.add_argument("--config", "-c")

    args.add_argument("--mapper", "-m", default="bwa", help="Available mappers: %s" % available_mappers())
    args.add_argument("--mapper-options", help="Custom maper options (advanced)")
    args.add_argument("--bam")
    args.add_argument("--variant", "-v", default="gatk", help="Available variant callers: %s" % available_callers())
    args.add_argument("--variant-options", help="Custom variant options (advanced)")
    args.add_argument("--vcf")
    args.add_argument("--filters", type=str, help="Filters to be applied to the VCF in key:value pairs, separated by comma (,). Available_filters: %s. Recommendations: GATK: mq_score:30,min_depth:10,ad_ratio:0.9 Mpileup: mq_score:30,min_depth:10,dp4_ratio:0.9" % available_filters())

    args.add_argument("--annotators", nargs="+", help="List of annotators to run before filters. Available: %s" % available_annotators())

    args.add_argument("--keep-temp", action="store_true", help="Keep intermediate files like BAMs and VCFs (default: False).")

    args.add_argument("--json", action="store_true", help="Also write variant positions in filtered vcf as json file (default: False).")
    args.add_argument("--json-info", action="store_true", help="When writing a json file, log some stats to stdout. (default: False).")

    return args 
Example 36
Project: aetros-cli   Author: aetros   File: AddCommand.py    License: MIT License 5 votes vote down vote up
def main(self, args):
        import aetros.const

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' add')
        parser.add_argument('id', nargs='?', help="Model name like peter/mnist/ef8009d83a9892968097cec05b9467c685d45453")
        parser.add_argument('local_path', nargs='?', help="File path to be added to the job head commit history")
        parser.add_argument('git_path', nargs='?', help="Path under which the file will be stored.")
        parser.add_argument('-m', help="Commit message")

        parsed_args = parser.parse_args(args)

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

        config = read_config()

        [model, job_id] = unpack_simple_job_id(parsed_args.id)
        ref = 'refs/aetros/job/' + job_id

        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?")

        git = Git(self.logger, None, config, model)
        git.job_id = job_id
        try:
            git.read_tree(ref)

            with open(parsed_args.local_path, 'rb') as f:
                id = git.commit_file(parsed_args.m or 'Added file', parsed_args.git_path or parsed_args.local_path, f.read())

                self.logger.info('Successfully committed to ' + id + '.')
                self.logger.info('Run "aetros job-push ' + git.job_id[0:9] + '" to upload changes to AETROS.')
        finally:
            git.clean_up() 
Example 37
Project: aetros-cli   Author: aetros   File: JobPullCommand.py    License: MIT License 5 votes vote down vote up
def main(self, args):
        import aetros.const

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' job-pull')
        parser.add_argument('id', help="Short or long job id, like ef8009d83a9892968097cec05b9467c685d45453")
        parser.add_argument('--model', help="Model name like peter/mnist. Per default from configuration.")
        parser.add_argument('-c', '--config', help="Default aetros.yml in current working directory or directories above.")

        parsed_args = parser.parse_args(args)

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

        home_config = read_home_config()
        config = find_config(parsed_args.config)
        model = parsed_args.model if parsed_args.model else config['model']

        if not model:
            print("No model defined. Use --model or switch into a directory where you executed 'aetros init model-name'.")
            sys.exit(2)

        full_id = git_has_remote_job(home_config, model, parsed_args.id)
        if not full_id:
            print("Error: Job not found on remote.")
            sys.exit(1)

        ref = 'refs/aetros/job/' + full_id
        git_dir = os.path.normpath(home_config['storage_dir'] + '/' + model + '.git')

        git_remote_url = 'git@%s:%s.git' % (home_config['host'], model)

        if not os.path.isdir(git_dir):
            subprocess.call([home_config['git'], '--bare', 'clone', git_remote_url, git_dir])

        print('Pull job %s of %s' % (parsed_args.id, model))
        setup_git_ssh(home_config)
        subprocess.call([home_config['git'], '--bare', '--git-dir', git_dir, 'fetch', 'origin', ref+':'+ref]) 
Example 38
Project: aetros-cli   Author: aetros   File: StartSimpleCommand.py    License: MIT License 5 votes vote down vote up
def main(self, args):
        import aetros.const

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
                                         prog=aetros.const.__prog__ + ' start-simple', description="Internal usage.")

        parser.add_argument('id', nargs='?', help='Job id, e.g. user/modelname/0db75a64acb74c27bd72c22e359de7a4c44a20e5 to start a pre-created job.')
        parser.add_argument('--fetch', action='store_true', help="Fetch job from server.")

        parsed_args = parser.parse_args(args)

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

        owner, name, id = unpack_full_job_id(parsed_args.id)

        job_backend = JobBackend(model_name=owner + '/' + name)
        job_backend.section('checkout')

        if parsed_args.fetch:
            job_backend.fetch(id)

        job_backend.load(id)
        job_backend.start()

        start_keras(self.logger, job_backend) 
Example 39
Project: aetros-cli   Author: aetros   File: ApiCommand.py    License: MIT License 5 votes vote down vote up
def main(self, args):
        import aetros.const

        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
                description="You can provide json in stdin to issue a POST call", prog=aetros.const.__prog__ + ' api')
        parser.add_argument('path', nargs='?', help="Request path + query, e.g. model/settings?name=owner/name")
        parser.add_argument('--method', nargs='?', help="Per default GET, if stdin data is given a POST. Alternatively provide a HTTP verb.")

        parsed_args = parser.parse_args(args)

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

        sys.stdout.write(api.request(parsed_args.path)) 
Example 40
Project: BerePi   Author: jeonghoonkang   File: tsdb_temperature.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_args():
    parser=argparse.ArgumentParser(description="how to run, watch.py", usage='use "%(prog)s --help" for more information', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-ip", "--ipaddress", default="0.0.0.0:0000", help="input ip address of iot db")
    parser.add_argument("-id", "--nodeid", default="-1", help="input id of iot device")
    args = parser.parse_args()
    return args 
Example 41
Project: BerePi   Author: jeonghoonkang   File: watch.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_args():
    parser=argparse.ArgumentParser(description="how to run, watch.py", usage='use "%(prog)s --help" for more information', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-ip", "--ipaddress", default="0.0.0.0:0000", help="input ip address of iot db")
    parser.add_argument("-id", "--nodeid", default="-1", help="input id of iot device")
    args = parser.parse_args()
    return args 
Example 42
Project: BerePi   Author: jeonghoonkang   File: useTSDB.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_args():
    story = 'OpenTSDB needs many arguments URL, start time, end time, port '
    usg = '\n python tsdb_read.py  -url x.x.x.x -port 4242 -start 2016110100 -end 2016110222, --help for more info'
    parser=argparse.ArgumentParser(description=story, usage=usg, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-url",    default="localhost", help="URL input, or run fails")
    parser.add_argument("-start",  default=None, help="start time input, like 2016110100")
    parser.add_argument("-end",    default=None, help="end time input, like 2016110223")
    parser.add_argument("-port",   default=4242, help="port input, like 4242")
    parser.add_argument("-recent", default=None, help="Time input for recent value")
    parser.add_argument("-m", default=None, help="metric ")
    args = parser.parse_args()
    
    #check args if valid
    url = args.url
    _ht = 'http://'
    if ( url[:7] != _ht ) : url = _ht + url
    port = args.port
    if  port == 80 : port = ''
    else : port = ":"+ str(port)
    url = url + port +'/api/query?'

    start = args.start
    if start != None : start = args.start
    end = args.end
    if end != None : end = args.end

    recent = args.port
    if recent != None : recent = args.recent

    m = args.m
    if m == None : exit("... please input metric name")
    
    return url, port, start, end, recent, m 
Example 43
Project: BerePi   Author: jeonghoonkang   File: put_test.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_args():

    story = 'OpenTSDB needs many arguments URL, start time, end time, port '
    usg = '\n python tsdb_read.py  -url x.x.x.x \
        -port 4242 -start 2016110100 -end 2016110222 \
        -rdm metric_name, -wm write_metric_name -tags="{id:911}" --help for more info'

    parser=argparse.ArgumentParser(description=story,
        usage=usg,
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument("-url",    default="127.0.0.1",
        help="URL input, or run fails")
    parser.add_argument("-start",  default='2016070100',
        help="start time input, like 2016110100")
    parser.add_argument("-port",   default=4242,
        help="port input, like 4242")
    parser.add_argument("-val", default=802,
        help="value which will be inserted to OpenTSDB")
    parser.add_argument("-wtm", default='__keti_test__',
        help="write-metric ")
    parser.add_argument("-tags", default="{'sensor':'_test_sensor_', 'desc':'_test_'}",
        help="tags ")
    args = parser.parse_args()

    #check args if valid
    url = args.url
    _ht = 'http://'
    if ( url[:7] != _ht ) : url = _ht + url
    port = args.port
    if  port == 80 : port = ''
    else : port = ":"+ str(port)
    url = url + port +'/api/put'


    wm = args.wtm
    if wm == None :
        print usg
        exit("... I can not do anything without metric")

    return url, wm, args.start, args.val, args.tags 
Example 44
Project: BerePi   Author: jeonghoonkang   File: tsdb_read.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_args():
    story = 'OpenTSDB needs many arguments URL, start time, end time, port '
    usg = '\n python tsdb_read.py  -url x.x.x.x -port 4242 -start 2016110100 -end 2016110222, --help for more info'
    parser=argparse.ArgumentParser(description=story, usage=usg, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-url",    default='localhost', help="URL input, or run fails")
    parser.add_argument("-start",  default=None, help="start time input, like 2016110100")
    parser.add_argument("-end",    default=None, help="end time input, like 2016110223")
    parser.add_argument("-port",   default='4242', help="port input, like 4242")
    parser.add_argument("-recent", default=None, help="Time input for recent value")
    parser.add_argument("-m", default=None, help="metric ")
    args = parser.parse_args()
    #check args if valid
    url = args.url
    port = args.port
    if port != None : port = ':' + args.port
    else : port = ''
    if url != None : url = 'http://' + url + port + '/api/query?'
    else : exit("... please input URL and other arguments")

    start = args.start
    if start != None : start = args.start
    end = args.end
    if end != None : end = args.end
    recent = args.port
    if recent != None : recent = args.recent
    m = args.m
    #print args
    return url, port, start, end, recent, m 
Example 45
Project: YAMDA   Author: daquang   File: erase_annoying_sequences.py    License: MIT License 5 votes vote down vote up
def get_args():
    parser = argparse.ArgumentParser(description="Train model.",
                                     epilog='\n'.join(__doc__.strip().split('\n')[1:]).strip(),
                                     formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-i', '--input', required=True,
                        help='Input FASTA file', type=str)
    parser.add_argument('-o', '--output', default=None,
                        help='Output FASTA file of negative sequences', type=str)
    args = parser.parse_args()
    return args 
Example 46
Project: grimoire   Author: RUB-SysSec   File: config.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __load_arguments(self):
        parser = ArgsParser(formatter_class=argparse.RawTextHelpFormatter)

        viz_modes = ["dot", "plot"]
        viz_modes_help = '<dot>\tvisulize kafl fuzzer tree\n' \
                         '<plot>\t\tplot performance and runtime data\n'

        parser.add_argument('work_dir', metavar='<Working Directory>', action=FullPath, type=create_dir,
                            help='Path to the working directory.')

        parser.add_argument('mode', metavar='<Mode>', choices=viz_modes, help=viz_modes_help)

        self.argument_values = vars(parser.parse_args()) 
Example 47
Project: grimoire   Author: RUB-SysSec   File: config.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __load_arguments(self):

        parser = ArgsParser(formatter_class=argparse.RawTextHelpFormatter)
        subparsers = parser.add_subparsers()

        parser_vm = subparsers.add_parser('VM', help="Full Virtual Machine Mode (RAM File / Overlay Files)",
                                          formatter_class=argparse.RawTextHelpFormatter)
        parser_vm.add_argument('ram_file', metavar='<RAM File>', action=FullPath, type=parse_is_file,
                               help='Path to the RAM file.')
        parser_vm.add_argument('overlay_dir', metavar='<Overlay Directory>', action=FullPath, type=parse_is_dir,
                               help='Path to the overlay directory.')
        parser.add_argument('-S', required=False, metavar='Snapshot', help='specifiy snapshot title (default: kafl).',
                            default="kafl", type=str)

        parser_kernel = subparsers.add_parser('Kernel', help="Lightweight Linux Mode (Kernel Image / initramfs)",
                                              formatter_class=argparse.RawTextHelpFormatter)
        parser_kernel.add_argument('kernel', metavar='<Kernel Image>', action=FullPath, type=parse_is_file,
                                   help='Path to the Kernel image.')
        parser_kernel.add_argument('initramfs', metavar='<Initramfs File>', action=FullPath, type=parse_is_file,
                                   help='Path to the initramfs file.')

        for sparser in [parser_vm, parser_kernel]:
            sparser.add_argument('executable', metavar='<Info Executable>', action=FullPath, type=parse_is_file,
                                 help='path to the info executable (kernel address dumper).')
            sparser.add_argument('mem', metavar='<RAM Size>', help='size of virtual RAM (default: 300).', default=300,
                                 type=int)
            sparser.add_argument('-v', required=False, help='enable verbose mode (./debug.log).', action='store_true',
                                 default=False)
            sparser.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 48
Project: upload-scripts   Author: openstreetcam   File: osc_tools.py    License: MIT License 5 votes vote down vote up
def get_args() -> list:
    """Method to create and configure a argument parser"""
    parser: ArgumentParser = ArgumentParser(prog='python osc_tools.py',
                                            formatter_class=RawTextHelpFormatter)

    subparsers = parser.add_subparsers(title='These are the available OSC commands',
                                       description='upload          Uploads sequences from a given'
                                                   ' path to OpenStreetCam\n'
                                                   'generate_exif   Generates Exif info for each '
                                                   'image from a metadata file',
                                       dest='sub command')
    subparsers.required = True
    create_parsers(subparsers)

    return parser.parse_args() 
Example 49
Project: upload-scripts   Author: openstreetcam   File: osc_tools.py    License: MIT License 5 votes vote down vote up
def add_generate_exif_parser(subparsers: ArgumentParser):
    """Adds generate exif parser"""
    generate_parser = subparsers.add_parser('generate_exif', formatter_class=RawTextHelpFormatter)
    generate_parser.set_defaults(func=exif_generation_command)
    generate_parser.add_argument('-p',
                                 '--path',
                                 required=True,
                                 help='Folder PATH with OSC metadata file and images')
    _add_logging_argument(generate_parser)

    return subparsers 
Example 50
Project: MIDAS   Author: snayfach   File: build_midas_db.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fetch_arguments():
	parser = argparse.ArgumentParser(
		formatter_class=argparse.RawTextHelpFormatter,
		usage=argparse.SUPPRESS,
		description="""
Description:
This script will allow you to build your own custom MIDAS database
Usage: build_midas_db.py indir mapfile outdir [options]
""")
	parser.add_argument('indir', type=str,
		help="""Path to directory of input genomes
Each subdirectory should be named according to a genome_id
Each subdirectory should contain (replace genome_id):
  genome_id.fna: Genomic DNA sequence in FASTA format
  genome_id.ffn: Gene DNA sequences in FASTA format
  genome_id.faa: Translated genes in FASTA format
""")
	parser.add_argument('mapfile', type=str,
		help="""Path to mapping file that specifies which genomes belonging to the same species.
The file should be tab-delimited file with a header and 3 fields:
  genome_id (CHAR): corresponds to subdirectory within INDIR
  species_id (CHAR): species identifier for genome_id
  rep_genome (0 or 1): indicator if genome_id should be used for SNP calling
""")
	parser.add_argument('outdir', type=str,
		help="Directory to store MIDAS database")
	parser.add_argument('--threads', type=str, metavar='INT', default=1,
		help="Number of threads to use (1)")
	parser.add_argument('--compress', action='store_true', default=False,
		help="Compress output files with gzip (False)")
	parser.add_argument('--max_species', type=int, default=float('inf'), metavar='INT',
		help="Maximum number of species to process from input (use all).\nUseful for quick tests")
	parser.add_argument('--max_genomes', type=int, default=float('inf'), metavar='INT',
		help="Maximum number of genomes to process per species (use all).\nUseful for quick tests")
	parser.add_argument('--max_length', type=int, default=20000, metavar='INT',
		help="Maximum gene length to use (20000). \nVery long genes can be problemmatic for VSEARCH")
	parser.add_argument('--resume', action='store_true', default=False,
		help="Resume database building without starting over from scratch (False)")

	args = vars(parser.parse_args())
	return args 
Example 51
Project: manly   Author: carlbordum   File: manly.py    License: MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(
        prog="manly",
        description="Explain how FLAGS modify a COMMAND's behaviour.",
        epilog=USAGE_EXAMPLE,
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument("command", nargs=argparse.REMAINDER, help="")
    parser.add_argument(
        "-v",
        "--version",
        action="version",
        version=VERSION,
        help="display version information and exit.",
    )
    args = parser.parse_args()

    if not len(args.command):
        print_err(
            "manly: missing COMMAND\nTry 'manly --help' for more information.",
        )
        sys.exit(1)

    title, output = manly(args.command)
    if output:
        print("\n%s" % title)
        print("=" * (len(title) - 8), end="\n\n")
        for flag in output:
            print(flag, end="\n\n")
    else:
        print_err("manly: No matching flags found.") 
Example 52
Project: passmaker   Author: bit4woo   File: passmaker.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description= \
        "Usage: python passmaker.py <OPTIONS> \n")

    menu_group = parser.add_argument_group('Menu Options')

    menu_group.add_argument('-o', '--output', help="password dict file", default=None)
    menu_group.add_argument('-i', '--interactive', help="interactive mode",action='store_true',default=False)
    menu_group.add_argument('-g', '--gui', help="GUI mode", action='store_true', default=False)

    argcomplete.autocomplete(parser)
    args = parser.parse_args()

    return args 
Example 53
Project: CAMISIM   Author: CAMI-challenge   File: argumenthandler_ga.py    License: Apache License 2.0 4 votes vote down vote up
def _get_parser_options(args=None, version="Prototype"):
		"""
		Parsing of passed arguments.

		@param args: Passed arguemnts

		@return: any
		"""
		description = """
	#######################################
	#    GenomeAnnotationPipeline         #
	#    Version {}#
	#######################################

	Pipeline for the extraction of marker genes, clustering and taxonomic classification""".format(version.ljust(25))
		parser = argparse.ArgumentParser(
			usage="python %(prog)s configuration_file_path",
			version="MetagenomeSimulationPipeline TC {}".format(version),
			description=description,
			formatter_class=argparse.RawTextHelpFormatter)
		parser.add_argument(
			"-verbose", "--verbose",
			action='store_true',
			default=False,
			help="display more information!")
		parser.add_argument(
			"-debug", "--debug_mode",
			action='store_true',
			default=False,
			help="tmp folders will not be deleted!")
		parser.add_argument(
			"-log", "--logfile",
			type=str,
			default=None,
			help="pipeline output will written to this log file")

		group_input = parser.add_argument_group('optional config arguments')
		group_input.add_argument(
			"-p", "--max_processors",
			default=None,
			type=int,
			help="number of available processors")
		group_input.add_argument("-s", "--phase", default=None, type=int, choices=[0, 1, 2, 3], help='''
0 -> Full run (Default)
1 -> Marker gene extraction
2 -> Gene alignment and clustering
3 -> Annotation of Genomes
''')
		group_input = parser.add_argument_group('required')
		group_input.add_argument("config_file", type=str, default=None, help="path to the configuration file of the pipeline")

		if args is None:
			return parser.parse_args()
		else:
			return parser.parse_args(args) 
Example 54
Project: simnibs   Author: simnibs   File: mni2subject_coords.py    License: GNU General Public License v3.0 4 votes vote down vote up
def parse_arguments(argv):

    transf_types_str = '\nnonl: Non-linear transformation.\n' + \
                       '6dof: 6 degrees of freedom affine transformation.\n' +\
                       '12dof: 12 degrees of freedom affine transformation.\n'

    csv_descrip = textwrap.dedent(
            '''
            CSV file with coordinates. The csv file must have the format
            Generic:
                Generic, pos_x, pos_y, pos_z, name, ...
            Positions will not be changed after transformation.

            Fiducial, Electrode, ReferenceElectrode:
                 Type, pos_x, pos_y, pos_z, name, whatever
                 Type, pos_x, pos_y, pos_z, pos2_x, pos2_y, pos2_z, name, ...
            Positions will be projected on skin after transformation.
            Type must be Fiducial, Electrode, or ReferenceElectrode.

            CoilPos:
                Type, pos_x, pos_y, pos_z, ez_x, ez_y, ez_z, ey_x, ey_y, ey_z, dist, name, ...
            Position will be adjusted after transformation to have specified distance to skin
            ''')

    parser = argparse.ArgumentParser(prog="mni2subject_coords",
                                     description="Transform coordinates "
                                     "from MNI space to subject space using the "
                                     "deformation fields calculated during the "
                                     "segmentation.",
                                     formatter_class=RawTextHelpFormatter)
    parser.add_argument('-m', "--m2mpath", dest='m2mpath', required=True,
                        help="path to m2m_{subjectID} directory, created in the "
                        "segmentation")
    parser.add_argument("-c", '--coords', dest='coords', nargs=3, action='store',
                        help="Input coordinates. 3 values separated by spaces",
                        default=None)
    parser.add_argument('-s', '--csv', dest='csv', required=False,
                        help=csv_descrip, default=None)
    parser.add_argument('-o', '--out', dest='out',
                        help="CSV file where the transformed coordinates will be saved. "
                        "Also prints a '.geo' file that can be visualized in gmsh "
                        "If not set, the values will be printed to the screen", default=None)
    parser.add_argument('-t', "--transformation_type", dest='t',
                        help='(optional) Type of transformation to use.'
                        '{0} Default: nonl'.format(transf_types_str), default='nonl',
                        choices=['nonl', '6dof', '12dof'])
    parser.add_argument('--version', action='version', version=__version__)
    return parser.parse_args(argv) 
Example 55
Project: simnibs   Author: simnibs   File: subject2mni_coords.py    License: GNU General Public License v3.0 4 votes vote down vote up
def parse_arguments(argv):

    transf_types_str = '\nnonl: Non-linear transformation.\n' + \
                       '6dof: 6 degrees of freedom affine transformation.\n' +\
                       '12dof: 12 degrees of freedom affine transformation.\n'

    csv_descrip = textwrap.dedent(
            '''
            CSV file with coordinates. The csv file must have the format
            Generic:
                Generic, pos_x, pos_y, pos_z, name, ...
            Positions will not be changed after transformation.

            Fiducial, Electrode, ReferenceElectrode:
                 Type, pos_x, pos_y, pos_z, name, whatever
                 Type, pos_x, pos_y, pos_z, pos2_x, pos2_y, pos2_z, name, ...

            CoilPos:
                Type, pos_x, pos_y, pos_z, ez_x, ez_y, ez_z, ey_x, ey_y, ey_z, dist, name, ...
            ''')

    parser = argparse.ArgumentParser(prog="subject2mni_coords",
                                     description="Transform coordinates "
                                     "from subject space to MNI space using the "
                                     "deformation fields calculated during the "
                                     "segmentation.",
                                     formatter_class=RawTextHelpFormatter)
    parser.add_argument('-m', "--m2mpath", dest='m2mpath', required=True,
                        help="path to m2m_{subjectID} directory, created in the "
                        "segmentation")
    parser.add_argument("-c", '--coords', dest='coords', nargs=3, action='store',
                        help="Input coordinates. 3 values separated by spaces",
                        default=None)
    parser.add_argument('-s', '--csv', dest='csv', required=False,
                        help=csv_descrip, default=None)
    parser.add_argument('-o', '--out', dest='out',
                        help="CSV file where the transformed coordinates will be saved. "
                        "Also prints a '.geo' file that can be visualized in gmsh "
                        "If not set, the values will be printed to the screen", default=None)
    parser.add_argument("--transformation_type", '-t', dest='t',
                        help='(optional) Type of transformation to use.'
                        '{0} Default: nonl'.format(transf_types_str), default='nonl',
                        choices=['nonl', '6dof', '12dof'])
    parser.add_argument('--version', action='version', version=__version__)
    return parser.parse_args(argv) 
Example 56
Project: misp42splunk   Author: remg427   File: jsonpath.py    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
def main(*argv):
    parser = argparse.ArgumentParser(
        description='Search JSON files (or stdin) according to a JSONPath expression.',
        formatter_class=argparse.RawTextHelpFormatter,
        epilog="""
        Quick JSONPath reference (see more at https://github.com/kennknowles/python-jsonpath-rw)

        atomics:
            $              - root object
            `this`         - current object

        operators:
            path1.path2    - same as xpath /
            path1|path2    - union
            path1..path2   - somewhere in between

        fields:
            fieldname       - field with name
            *               - any field
            [_start_?:_end_?] - array slice
            [*]             - any array index
    """)



    parser.add_argument('expression', help='A JSONPath expression.')
    parser.add_argument('files', metavar='file', nargs='*', help='Files to search (if none, searches stdin)')

    args = parser.parse_args(argv[1:])

    expr = parse(args.expression)
    glob_patterns = args.files

    if len(glob_patterns) == 0:
        # stdin mode
        print_matches(find_matches_for_file(expr, sys.stdin))
    else:
        # file paths mode
        for pattern in glob_patterns:
            for filename in glob.glob(pattern):
                with open(filename) as f:
                    print_matches(find_matches_for_file(expr, f)) 
Example 57
Project: misp42splunk   Author: remg427   File: jsonpath.py    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
def main(*argv):
    parser = argparse.ArgumentParser(
        description='Search JSON files (or stdin) according to a JSONPath expression.',
        formatter_class=argparse.RawTextHelpFormatter,
        epilog="""
        Quick JSONPath reference (see more at https://github.com/kennknowles/python-jsonpath-rw)

        atomics:
            $              - root object
            `this`         - current object

        operators:
            path1.path2    - same as xpath /
            path1|path2    - union
            path1..path2   - somewhere in between

        fields:
            fieldname       - field with name
            *               - any field
            [_start_?:_end_?] - array slice
            [*]             - any array index
    """)



    parser.add_argument('expression', help='A JSONPath expression.')
    parser.add_argument('files', metavar='file', nargs='*', help='Files to search (if none, searches stdin)')

    args = parser.parse_args(argv[1:])

    expr = parse(args.expression)
    glob_patterns = args.files

    if len(glob_patterns) == 0:
        # stdin mode
        print_matches(find_matches_for_file(expr, sys.stdin))
    else:
        # file paths mode
        for pattern in glob_patterns:
            for filename in glob.glob(pattern):
                with open(filename) as f:
                    print_matches(find_matches_for_file(expr, f)) 
Example 58
Project: toil-scripts   Author: BD2KGenomics   File: spladder_pipeline.py    License: Apache License 2.0 4 votes vote down vote up
def main():
    """
    This Toil pipeline aligns reads and performs alternative splicing analysis.

    Please read the README.md located in the same directory for run instructions.
    """
    # Define Parser object and add to toil
    url_prefix = 'https://s3-us-west-2.amazonaws.com/cgl-pipeline-inputs/'
    parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--config', required=True,
                        help='Path to configuration file for samples, one per line. UUID,URL_to_bamfile. '
                             'The URL may be a standard "http://", a "file://<abs_path>", or "s3://<bucket>/<key>"')
    parser.add_argument('--gtf', help='URL to annotation GTF file',
                        default=url_prefix + 'rnaseq_cgl/gencode.v23.annotation.gtf')
    parser.add_argument('--gtf-pickle', help='Pickled GTF file',
                        default=url_prefix + 'spladder/gencode.v23.annotation.gtf.pickle')
    parser.add_argument('--gtf-m53', help='M53 preprocessing annotation table',
                        default=url_prefix + 'spladder/gencode.v23.annotation.gtf.m53')
    parser.add_argument('--positions', help='URL to SNP positions over genes file (TSV)',
                        default=url_prefix + 'spladder/positions_fixed.tsv')
    parser.add_argument('--genome', help='URL to Genome fasta',
                        default=url_prefix + 'rnaseq_cgl/hg38_no_alt.fa')
    parser.add_argument('--genome-index', help='Index file (fai) of genome',
                        default=url_prefix + 'spladder/hg38_no_alt.fa.fai')
    parser.add_argument('--ssec', default=None, help='Path to master key used for downloading encrypted files.')
    parser.add_argument('--output-s3-dir', default=None, help='S3 Directory of the form: s3://bucket/directory')
    parser.add_argument('--output-dir', default=None, help='full path where final results will be output')
    parser.add_argument('--sudo', action='store_true', default=False,
                        help='Set flag if sudo is required to run Docker.')
    parser.add_argument('--star-index', help='URL to download STAR Index built from HG38/gencodev23 annotation.',
                        default=url_prefix + 'rnaseq_cgl/starIndex_hg38_no_alt.tar.gz')
    parser.add_argument('--fwd-3pr-adapter', help="Sequence for the FWD 3' Read Adapter.", default='AGATCGGAAGAG')
    parser.add_argument('--rev-3pr-adapter', help="Sequence for the REV 3' Read Adapter.", default='AGATCGGAAGAG')
    Job.Runner.addToilOptions(parser)
    args = parser.parse_args()
    # Sanity Checks
    if args.config:
        assert os.path.isfile(args.config), 'Config not found at: {}'.format(args.config)
    if args.ssec:
        assert os.path.isfile(args.ssec), 'Encryption key not found at: {}'.format(args.config)
    if args.output_s3_dir:
        assert args.output_s3_dir.startswith('s3://'), 'Wrong format for output s3 directory'
    # Program checks
    for program in ['curl', 'docker']:
        assert which(program), 'Program "{}" must be installed on every node.'.format(program)

    Job.Runner.startToil(Job.wrapJobFn(parse_input_samples, args), args) 
Example 59
Project: firmware_password_manager   Author: univ-of-utah-marriott-library-apple   File: firmware_password_manager.py    License: MIT License 4 votes vote down vote up
def main():
    """
    This should not be blank.
    """
    master_version = "2.5"

    logo = """
         /_ _/ /_ _/   University of Utah
          _/    _/    Marriott Library
         _/    _/    Mac Group
        _/    _/   https://apple.lib.utah.edu/
         _/_/    https://github.com/univ-of-utah-marriott-library-apple


        """
    desc = "Manages the firmware password on Apple Macintosh computers."

    #
    # require root to run.
    if os.geteuid():
        print("Must be root to run script.")
        sys.exit(2)

    #
    # parse option definitions
    parser = argparse.ArgumentParser(description=logo+desc, formatter_class=RawTextHelpFormatter)

    #
    # required, mutually exclusive commands
    prime_group = parser.add_argument_group('Required management settings', 'Choosing one of these options is required to run FWPM. They tell FWPM how you want to manage the firmware password.')
    subprime = prime_group.add_mutually_exclusive_group(required=True)
    subprime.add_argument('-c', '--configfile', help='Read configuration file')

    parser.add_argument('-b', '--reboot', action="store_true", default=False, help='Reboots the computer after the script completes successfully.')
    parser.add_argument('-t', '--testmode', action="store_true", default=False, help='Test mode. Verbose logging, will not delete keyfile.')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + master_version)

    args = parser.parse_args()

    if args.testmode:
        print(args)

    #
    # Open log file
    try:
        log_path = '/var/log/' + 'FWPW_Manager_' + master_version
        logging.basicConfig(filename=log_path, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
        logger = logging.getLogger(__name__)
        logger.info("Running Firmware Password Manager " + master_version)
    except:
        logger = None

    FWPM_Object(args, logger, master_version) 
Example 60
Project: dipper   Author: monarch-initiative   File: omia-integration.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(
        description='OMIA integration test',
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument(
        '--input', '-i', type=str, required=True, help='Location of input ttl file')

    args = parser.parse_args()

    graph = ConjunctiveGraph()
    graph.parse(args.input, format=rdflib_util.guess_format(args.input))

    # "is model of": "RO:0003301"
    # is_model_of = URIRef('OBO:RO_0003301')
    is_model_of = URIRef('http://purl.obolibrary.org/obo/RO_0003301')

    # if we curie_map & globaltt here we could ...
    # (pfx lcl) = globaltt["is model of"].split(':')
    # iri = curie_map[pfx] + '_'.join((pfx, lcl))
    # is_model_of = URIRef(iri)

    models = graph.subject_objects(is_model_of)
    model_len = len(set(list(models)))

    if model_len < EXPECTED_PAIRS:
        LOG.error(
            "Not enough <RO:is model of> predicates in graph: found {}, "
            "expected {} check omia log for warnings".format(
                model_len, EXPECTED_PAIRS))
        exit(1)
    # else:
    #    LOG.info(
    #        "Found {} model_of predicates in graph, expected at least: {}".format(
    #            model_len, EXPECTED_PAIRS))

    breed = 'https://monarchinitiative.org/model/OMIA-breed:758'
    disease = 'http://omim.org/entry/305100'

    omim_diseases = graph.objects(
        subject=URIRef(breed),
        predicate=is_model_of
    )

    if list(omim_diseases) != [URIRef(disease)]:
        LOG.error("Missing breed to omim triple for %s", breed)
        LOG.error(list(omim_diseases))
        exit(1)

    LOG.info("PASSED")