Beispiel #1
0
 def get_parser(self):
     p = ArgumentParser(self.description)
     p.usage = "save name [-h] [-f] [--metadata value [--metadata value ...]]"
     p.epilog = "See documentation for a list of required and optional metadata"
     p.add_argument(
         '-f',
         '--force',
         action='store_true',
         default=False,
         help='Force uploading even if it overwrites an existing image')
     p.add_argument('--gzip',
                    action='store_true',
                    default=False,
                    help='Upload the image compressed with gzip.')
     p.add_argument('--resize',
                    type=int,
                    default=0,
                    help='create an image with a new size (in MB)')
     p.add_argument('--verbose',
                    action='store_true',
                    default=False,
                    help='display verbose output during snapshot')
     p.add_argument(
         '--clean',
         action='store_true',
         default=False,
         help=
         'Remove any existing local snapshots before creating a new one.')
     return p
Beispiel #2
0
def create_argument_parser():
    """Create the argument parser."""

    parser = ArgumentParser(add_help=False)
    parser.usage = "gcovr [options] [search_paths...]"
    parser.description = (
        "A utility to run gcov and summarize the coverage in simple reports.")

    parser.epilog = "See <http://gcovr.com/> for the full manual."

    options = parser.add_argument_group("Options")
    options.add_argument("-h",
                         "--help",
                         help="Show this help message, then exit.",
                         action="help")
    options.add_argument(
        "--version",
        help="Print the version number, then exit.",
        action="store_true",
        dest="version",
        default=False,
    )

    argument_parser_setup(parser, options)

    return parser
Beispiel #3
0
def add_environments(
        parser: argparse.ArgumentParser,
        completer: CompositeActionCompletionFinder,
        controller_mode: ControllerMode,
        target_mode: TargetMode,
) -> None:
    """Add arguments for the environments used to run ansible-test and commands it invokes."""
    no_environment = controller_mode == ControllerMode.NO_DELEGATION and target_mode == TargetMode.NO_TARGETS

    parser.set_defaults(no_environment=no_environment)

    if no_environment:
        return

    parser.set_defaults(target_mode=target_mode)

    add_global_options(parser, controller_mode)
    add_legacy_environment_options(parser, controller_mode, target_mode)
    action_types = add_composite_environment_options(parser, completer, controller_mode, target_mode)

    sections = [f'{heading}\n{content}'
                for action_type, documentation_state in CompositeAction.documentation_state.items() if action_type in action_types
                for heading, content in documentation_state.sections.items()]

    if not get_ci_provider().supports_core_ci_auth():
        sections.append('Remote provisioning options have been hidden since no Ansible Core CI API key was found.')

    sections.append(get_epilog(completer))

    parser.formatter_class = argparse.RawDescriptionHelpFormatter
    parser.epilog = '\n\n'.join(sections)
Beispiel #4
0
def _get_args():
    parser = ArgumentParser(prog='quickgist',
                            description='quickgist is a simple command line '
                                        'tool for creating gists.',
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('sources', nargs='*',
                        help='gist content sources, ex: test.txt, '
                             'test1.txt test2.txt, test/*.txt')
    parser.add_argument('-f', type=str, default='',
                        help='gist filename, only used for stdin '
                             'or to override single input filename')
    parser.add_argument('-d', type=str, default='', help='gist description')
    parser.add_argument('-p', default=False, action='store_true',
                        help='private gist')
    parser.add_argument('-l', default=False, action='store_true',
                        help='long url, will not shorten')
    parser.add_argument('-nl', default=False, action='store_true',
                        help='suppress newline after url, good for xclip')
    parser.add_argument('-v', action='version', version='%(prog)s ' +
                                                        __version__)
    parser.epilog = """Examples:
    $ quickgist file.txt
    $ quickgist -d "some files" file.txt src/*.py
    $ cat foo | quickgist -f foo.txt

Notes:
    Please define an environment variable GIST_TOKEN with your
    GitHub personal access token.

    $ export GIST_TOKEN="YOUR_TOKEN_HERE"
    """

    return parser.parse_args()
Beispiel #5
0
def add_parameters(parser: argparse.ArgumentParser) -> None:
    """Adds parameters
    Arguments:
        parser: instance of argparse
    """
    supported_files = [FILE_NAME_CSV + ': basic CSV file with calculated values']
    if __internal__.get_algorithm_definition_bool('WRITE_GEOSTREAMS_CSV', True):
        supported_files.append(FILE_NAME_BETYDB_CSV + ': TERRA REF Geostreams compatible CSV file')
    if __internal__.get_algorithm_definition_bool('WRITE_BETYDB_CSV', True):
        supported_files.append(FILE_NAME_BETYDB_CSV + ': BETYdb compatible CSV file')

    parser.description = 'Plot level RGB algorithm: ' + __internal__.get_algorithm_name() + \
                         ' version ' + __internal__.get_algorithm_definition_str('VERSION', 'x.y')

    parser.add_argument('--csv_path', help='the path to use when generating the CSV files')
    parser.add_argument('--geostreams_csv', action='store_true',
                        help='override to always create the TERRA REF Geostreams-compatible CSV file')
    parser.add_argument('--betydb_csv', action='store_true', help='override to always create the BETYdb-compatible CSV file')

    parser.add_argument('germplasm_name', type=str, help='name of the cultivar associated with the plot')

    parser.epilog = 'The following files are created in the specified csv path by default: ' + \
                    '\n  ' + '\n  '.join(supported_files) + '\n' + \
                    ' author ' + __internal__.get_algorithm_definition_str('ALGORITHM_AUTHOR', 'mystery author') + \
                    ' ' + __internal__.get_algorithm_definition_str('ALGORITHM_AUTHOR_EMAIL', '(no email)')
Beispiel #6
0
 def decorate_parser(api: Api, parser: argparse.ArgumentParser) -> None:
     parser.add_argument(
         "--pts",
         help="which frame to make screenshot of",
         type=lambda value: Pts(api, value),
         default="cf",
     )
     parser.add_argument(
         "-p",
         "--path",
         help="path to save the screenshot to",
         type=lambda value: FancyPath(api, value),
         default="",
     )
     parser.add_argument(
         "-i",
         "--include-subs",
         help='whether to "burn" the subtitles into the screenshot',
         action="store_true",
     )
     parser.add_argument(
         "--width",
         help="width of the screenshot (by default, original video width)",
         type=int,
     )
     parser.add_argument(
         "--height",
         help=(
             "height of the screenshot (by default, original video height)"
         ),
         type=int,
     )
     parser.epilog = ("If only either of width or height is given, "
                      "the command tries to maintain aspect ratio.")
Beispiel #7
0
    def get_parser(self):
        p = ArgumentParser(self.description)
        p.formatter_class = argparse.RawDescriptionHelpFormatter
        p.add_argument('-a', '--all', action='store_true', default=False,
                       help="Display all images")
        p.add_argument('-l', '--long', action='store_true', default=False,
                       help='Display extra information for each image')
        p.add_argument('--sharedwith', action='store_true', default=False,
                       help='modifier flag.  See epilog for examples.')
        g = p.add_mutually_exclusive_group()
        g.add_argument('-u', '--user', help='List images owned by USER')
        g.add_argument('-g', '--group', help="List images shared with GROUP.")
        p.epilog = """\
Example Usages:

    repoman list
        list the current users images

    repoman list --sharedwith
        list all images shared with the current user

    repoman list --user bob
        list all images owned by the user 'bob'

    repoman list --sharedwith --user bob
        list all images shared with the user 'bob'

    repoman list --group babar
        list all images accessible by members of the 'babar' group

    repoman list --sharedwith --group babar
        has the same effect as the previous example."""

        return p
Beispiel #8
0
def _configure_arg_parser():
    parser = ArgumentParser(prog='ties-validate',
                            formatter_class=RawDescriptionHelpFormatter)
    parser.usage = 'ties-validate [-h] [--version] [FILE]...'
    parser.description = 'Validate FILE(s), or standard input, against the TIES 0.9 schema.'
    parser.epilog = ('''\
If FILE arguments are provided, attempts to validate all files. FILE arguments may be provided as either file paths or shell globs.

If no FILE arguments are provided, attempts to read a single JSON object from stdin and validate it.

Returns non-zero exit code if one or more input files fail to validate successfully.
''')
    parser.add_argument(
        'files',
        metavar='FILE',
        nargs='*',
        help=
        'the path to the JSON file(s) to be validated against the schema or - to read from stdin'
    )
    parser.add_argument('--version',
                        action=VersionAction,
                        version="TIES Schema Validator\n{}".format(
                            version_string()),
                        help='prints version information')
    return parser
Beispiel #9
0
def parse_args():
    p = ArgumentParser(description='Verify the checksum for a single file', formatter_class=RawDescriptionHelpFormatter)
    p.add_argument('file', help='The file to verify')

    hash_len_str = '; '.join('{} = {}'.format(k,v) for k,v in _algs_by_length.items())
    p.add_argument('-a', '--algorithm', default=None, choices=hashlib.algorithms_available, metavar='ALGORITHM',
                   help=f'Which algorithm to use for the hash. When comparing two files using '
                        f'the --original flag, the default is {_default_alg}. When checking '
                        f'against an existing checksum, the default behavior is to guess the '
                        f'algorithm from the length of the checksum ({hash_len_str}). If the '
                        f'length is unexpected, an error occurs.')

    p.epilog = 'The algorithms available on this computer are:\n\n{}\n\nHowever, be aware that some require extra information and will not work.'.format(_format_alg_list())
    
    chk_grp = p.add_mutually_exclusive_group()
    chk_grp.add_argument('-c', '--checksum', help='The expected checksum for the file. If not given, it can be read from stdin ')
    chk_grp.add_argument('-o', '--original', help='An original file to compare the checksum against.')
    
    v_grp = p.add_mutually_exclusive_group()
    v_grp.add_argument('-v', '--verbose', action='store_const', const=2, dest='verbose', default=1,
                   help='Print the given and computed checksum for manual verification')
    v_grp.add_argument('-q', '--quiet', action='store_const', const=0, dest='verbose',
                   help='Silence all printing to the command line. The success or failure will only be communicated '
                        'by the exit code. 0 means the file\'s checksum matched, 2 means it did not. 1 indicates an error.')

    return vars(p.parse_args())
Beispiel #10
0
def create_argument_parser():
    """Create the argument parser."""

    parser = ArgumentParser(add_help=False)
    parser.usage = "gcovr [options] [search_paths...]"
    parser.description = \
        "A utility to run gcov and summarize the coverage in simple reports."

    parser.epilog = "See <http://gcovr.com/> for the full manual."

    options = parser.add_argument_group('Options')
    options.add_argument(
        "-h", "--help",
        help="Show this help message, then exit.",
        action="help"
    )
    options.add_argument(
        "--version",
        help="Print the version number, then exit.",
        action="store_true",
        dest="version",
        default=False
    )

    argument_parser_setup(parser, options)

    return parser
Beispiel #11
0
 def add_parameters(self, parser: argparse.ArgumentParser) -> None:
     """Adds processing parameters to existing parameters
     Arguments:
         parser: instance of argparse
     """
     # pylint: disable=no-self-use
     parser.epilog = configuration.TRANSFORMER_NAME + ' version ' + configuration.TRANSFORMER_VERSION + \
                     ' author ' + configuration.AUTHOR_NAME + ' ' + configuration.AUTHOR_EMAIL
Beispiel #12
0
def build_parser():
    """Build the argument parser."""

    # Map of top-level commands and their setup functions/description
    # New top-level commands should be added to this dictionary
    commands = StreamAlertCLICommandRepository.command_parsers()

    description_template = """
StreamAlert v{}

Configure, test, build, and deploy StreamAlert

Available Commands:

{}

For additional help with any command above, try:

        {} [command] --help
"""

    parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter,
                            prog=__file__)

    parser.add_argument('-v', '--version', action='version', version=version)

    parser.add_argument(
        '-d',
        '--debug',
        help=
        'enable debugging logger output for all of the StreamAlert loggers',
        action='store_true')

    # Dynamically generate subparsers, and create a 'commands' block for the prog description
    command_block = []
    subparsers = parser.add_subparsers(dest='command', required=True)
    command_col_size = max([len(command) for command in commands]) + 10
    for command in sorted(commands):
        setup_subparser_func, description = commands[command]
        subparser = generate_subparser(subparsers,
                                       command,
                                       description=description)

        # If there are additional arguments to set for this command, call its setup function
        if setup_subparser_func:
            setup_subparser_func(subparser)

        command_block.append('\t{command: <{pad}}{description}'.format(
            command=command, pad=command_col_size, description=description))

    # Update the description on the top level parser
    parser.description = description_template.format(version,
                                                     '\n'.join(command_block),
                                                     __file__)

    parser.epilog = 'Issues? Please report here: https://github.com/airbnb/streamalert/issues'

    return parser
Beispiel #13
0
 def add_parameters(self, parser: argparse.ArgumentParser) -> None:
     """Adds processing parameters to existing parameters
     Arguments:
         parser: instance of argparse
     """
     # pylint: disable=no-self-use
     parser.epilog = str(self.configuration.transformer_name) + ' version ' \
                     + str(self.configuration.transformer_version) + ' author ' + str(
         self.configuration.author_name) + ' ' + str(self.configuration.author_email)
Beispiel #14
0
def collect_arguments():
    parser = ArgumentParser()
    parser.prog = "pycollect"
    parser.description = 'collector: collects and sends stats to carbon'

    parser.add_argument('-m',
                        '--metric',
                        required=True,
                        help='metric path where to store data')
    parser.add_argument('-V',
                        '--verbose',
                        action='store_true',
                        help='print data to stdout before sending to server')
    parser.add_argument('-s',
                        '--server',
                        required=True,
                        help='carbon server address')
    parser.add_argument('-p',
                        '--port',
                        default=2003,
                        help='carbon server port, default 2003')
    parser.add_argument('-D',
                        '--daemon',
                        action='store_true',
                        help='run as daemon, sends data at regular intervals')
    parser.add_argument('-i',
                        '--interval',
                        type=float,
                        default=5.0,
                        help='interval to send data in daemon mode, \
                        defaults 5s')
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s ' + VERSION)

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-c',
                       '--value',
                       default=False,
                       type=int_or_float,
                       help='metric value to send, must be int or \
                       float ')
    group.add_argument('-P',
                       '--plugin',
                       default=False,
                       help='call plugin to collect metric data')
    group.add_argument('-S',
                       '--script',
                       default=False,
                       help='get value from script outpout')
    parser.epilog = 'metric must be in standard collectd format e.g.  hostname.stats.command.[time|data]'
    args = parser.parse_args()
    if args.value is not False and args.daemon is True:
        parser.error(
            'Can not run in Daemon mode with fixed value, use Script or Plugin mode'
        )
    return args
Beispiel #15
0
    def sample_usage(self, parser: ArgumentParser, intent: str, commands: list):
        parser.formatter_class = argparse.RawDescriptionHelpFormatter
        if not self.sample_usage_text:
            self.epilog_text = parser.epilog
            self.sample_usage_text = "sample usages:\n\n"

        self.sample_usage_text += intent + "\n  "
        self.sample_usage_text += "\n  ".join(commands) + "\n\n"

        parser.epilog = self.sample_usage_text + self.epilog_text
Beispiel #16
0
def main() -> None:
  parser = ArgumentParser(prog='pat', description='create or apply a .pat patch file.')
  parser.epilog = "for help with a specific command, pass '-h' to that command."

  subs = parser.add_subparsers()
  subs.required = True
  subs.dest = 'command'


  sub_create = subs.add_parser('create',
    help='[original] [modified] [patch]: create an empty .pat file at [patch] referencing [original], and copy [original] to [modified].')

  sub_create.set_defaults(handler=main_create)

  sub_create.add_argument('original',
    help='source file to use as the original (left/minus) side of the patch.')

  sub_create.add_argument('modified',
    help='path at which to copy the modified (right/plus) side of the patch; must not exist.')

  sub_create.add_argument('patch',
    help='path at which to create the new empty .pat file; must not exist.')


  sub_diff = subs.add_parser('diff',
    help='[original] [modified] [out]?: create .pat style diff between [original] and [modified], writing it to [out] or stdout.')

  sub_diff.set_defaults(handler=main_diff)

  sub_diff.add_argument('original', type=FileType('r'),
    help='source file to use as the original (left/minus) side of the patch.')

  sub_diff.add_argument('modified', type=FileType('r'),
    help='source file to use as the modified (right/plus) side of the patch.')

  sub_diff.add_argument('out', nargs='?', type=FileType('w'), default='-',
    help='output path (defaults to stdout)')

  sub_diff.add_argument('-min-context', type=int, default=3,
    help='minimum number of lines of context to show before each hunk.')


  sub_apply = subs.add_parser('apply',
    help='[patch] [out]?: apply a [patch] to the source file specified in that patch, and write it to [out] or stdout.')

  sub_apply.set_defaults(handler=main_apply)

  sub_apply.add_argument('patch', type=FileType('r'),
    help='input .pat path to apply')

  sub_apply.add_argument('out', nargs='?', type=FileType('w'), default='-',
    help='output path (defaults to stdout)')

  args = parser.parse_args()
  args.handler(args)
Beispiel #17
0
    def sample_usage(self, parser: ArgumentParser, intent: str,
                     commands: list):
        parser.formatter_class = argparse.RawDescriptionHelpFormatter
        if not self.sample_usage_text:
            self.epilog_text = parser.epilog
            self.sample_usage_text = 'sample usages:\n\n'

        self.sample_usage_text += intent + '\n  '
        self.sample_usage_text += '\n  '.join(commands) + '\n\n'

        parser.epilog = self.sample_usage_text + self.epilog_text
def add_export_arguments(parser: argparse.ArgumentParser):
    """Defines formal arguments for the 'chado export' sub-command"""
    parser.epilog = "For detailed usage information type '" + parser.prog + " <command> -h'"
    subparsers = parser.add_subparsers()
    for command, description in export_commands().items():
        # Create subparser and add general and specific formal arguments
        sub = subparsers.add_parser(command,
                                    description=description,
                                    help=description)
        add_general_arguments(sub)
        add_export_arguments_by_command(command, sub)
Beispiel #19
0
def setup_parser():
    parser = ArgumentParser(
        prog="erdpy",
        usage="erdpy [-h] [-v] [--verbose] COMMAND-GROUP [-h] COMMAND ...",
        description="""
-----------
DESCRIPTION
-----------
erdpy is part of the elrond-sdk and consists of Command Line Tools and Python SDK
for interacting with the Blockchain (in general) and with Smart Contracts (in particular).

erdpy targets a broad audience of users and developers.
https://docs.elrond.com/tools/erdpy.
        """,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser._positionals.title = "COMMAND GROUPS"
    parser._optionals.title = "TOP-LEVEL OPTIONS"

    parser.add_argument("-v",
                        "--version",
                        action="version",
                        version=f"erdpy {__version__}")
    parser.add_argument("--verbose", action="store_true", default=False)

    subparsers = parser.add_subparsers()
    commands: List[Any] = []

    commands.append(erdpy.cli_contracts.setup_parser(subparsers))
    commands.append(erdpy.cli_transactions.setup_parser(subparsers))
    commands.append(erdpy.cli_validators.setup_parser(subparsers))
    commands.append(erdpy.cli_accounts.setup_parser(subparsers))
    commands.append(erdpy.cli_wallet.setup_parser(subparsers))
    commands.append(erdpy.cli_network.setup_parser(subparsers))
    commands.append(erdpy.cli_cost.setup_parser(subparsers))
    commands.append(erdpy.cli_dispatcher.setup_parser(subparsers))
    commands.append(erdpy.cli_blockatlas.setup_parser(subparsers))
    commands.append(erdpy.cli_deps.setup_parser(subparsers))
    commands.append(erdpy.cli_config.setup_parser(subparsers))
    commands.append(erdpy.cli_block.setup_parser(subparsers))
    commands.append(erdpy.cli_testnet.setup_parser(subparsers))
    commands.append(erdpy.cli_data.setup_parser(subparsers))

    parser.epilog = """
----------------------
COMMAND GROUPS summary
----------------------
"""
    for choice, sub in subparsers.choices.items():
        parser.epilog += (f"{choice.ljust(30)} {sub.description}\n")

    return parser
Beispiel #20
0
    def configure(self, parser: ArgumentParser):
        super().configure(parser)
        parser.add_argument('-i', '--interactive', action='store_true', help='Pass STDIN to the container')
        parser.add_argument('-t', '--tty', action='store_true', help='Allocate a pseudo-TTY')
        parser.add_argument('-u', '--user', type=str, default=None,
                            help='Container username or UID (format: <name|uid>[:<group|gid>])')
        parser.add_argument('--no-sync', action='store_true', help='Don\'t sync the project before running the script')

        # add the "double-dash" argument to the usage message
        parser.prog = 'spotty exec'
        parser.usage = parser.format_usage()[7:-1] + ' -- COMMAND [args...]\n'
        parser.epilog = 'The double dash (--) separates the command that you want to execute inside the container ' \
                        'from the Spotty arguments.'
Beispiel #21
0
    def add_parameters(self, parser: argparse.ArgumentParser):
        """Adds parameters
        Arguments:
            parser: instance of argparse.ArgumentParser
        """
        # pylint: disable=no-self-use
        parser.add_argument(
            '--odm_overrides',
            type=str,
            help='file containing OpenDroneMap configuration overrides')

        parser.epilog = "accepts a list of files and folders following command line parameters" + \
                        ("\n" + parser.epilog) if parser.epilog else ""
Beispiel #22
0
def parse_args():
    parser = ArgumentParser()
    parser.description = "Сравнение набора слов и шаблона, описывающего эти слова с помощью граммем"
    parser.epilog = """Примеры использования:
    -------------------------------------------------------------------------
    mgrep --sentence 'Ящерица' --pattern 'anim'
    -------------------------------------------------------------------------
    mgrep --sentence 'Ящерица Ящер' --pattern='NOUN,anim,femn NOUN,anim,masc'
    -------------------------------------------------------------------------
    mgrep --sentence 'Ящерица хотькакоеслово' --pattern='NOUN *'
    """
    parser.add_argument("--pattern", type=str, required=True, help="Шаблон")
    parser.add_argument("--sentence", type=str, required=True, help="Фраза")
    return parser.parse_args()
Beispiel #23
0
 def get_parser(self):
     p = ArgumentParser(self.description)
     p.usage = "save name [-h] [-f] [--metadata value [--metadata value ...]]"
     p.epilog = "See documentation for a list of required and optional metadata"
     p.add_argument(
         "-f",
         "--force",
         action="store_true",
         default=False,
         help="Force uploading even if it overwrites an existing image",
     )
     p.add_argument("--gzip", action="store_true", default=False, help="Upload the image compressed with gzip.")
     p.add_argument("--resize", help="create an image with a new size (in MB)")
     return p
Beispiel #24
0
 def get_parser(self):
     p = ArgumentParser(self.description)
     p.usage = "save name [-h] [-f] [--metadata value [--metadata value ...]]"
     p.epilog = "See documentation for a list of required and optional metadata"
     p.add_argument('-f', '--force', action='store_true', default=False,
                    help='Force uploading even if it overwrites an existing image')
     p.add_argument('--gzip', action='store_true', default=False,
                    help='Upload the image compressed with gzip.')
     p.add_argument('--resize', type=int, default=0,
                    help='create an image with a new size (in MB)')
     p.add_argument('--verbose', action='store_true', default=False,
                    help='display verbose output during snapshot')         
     p.add_argument('--clean', action='store_true', default=False,
                    help='Remove any existing local snapshots before creating a new one.')
     return p
Beispiel #25
0
    def add_parameters(self, parser: argparse.ArgumentParser) -> None:
        """Adds processing parameters to existing parameters
        Arguments:
            parser: instance of argparse
        """
        # pylint: disable=no-self-use
        parser.add_argument(
            '--logging',
            '-l',
            nargs='?',
            default=os.getenv("LOGGING"),
            help='file or url or logging configuration (default=None)')

        parser.epilog = configuration.TRANSFORMER_NAME + ' version ' + configuration.TRANSFORMER_VERSION + \
                        ' author ' + configuration.AUTHOR_NAME + ' ' + configuration.AUTHOR_EMAIL
Beispiel #26
0
 def get_parser(self):
     p = ArgumentParser(self.description)
     p.usage = "save name [-h] [-f] [--metadata value [--metadata value ...]]"
     p.epilog = "See documentation for a list of required and optional metadata"
     p.add_argument(
         '-f',
         '--force',
         action='store_true',
         default=False,
         help='Force uploading even if it overwrites an existing image')
     p.add_argument('--gzip',
                    action='store_true',
                    default=False,
                    help='Upload the image compressed with gzip.')
     p.add_argument('--resize',
                    help='create an image with a new size (in MB)')
     return p
Beispiel #27
0
 def _init_argparse(self, parser: argparse.ArgumentParser) -> None:
     parser.add_argument(
         '-H',
         action='store_false',
         help=
         'do not display headers and separate fields by a single tab (scripted mode)'
     )
     parser.add_argument('-o',
                         metavar="FIELDS",
                         help='comma-separated list of fields to display')
     parser.add_argument('-p',
                         action='store_true',
                         help='display numbers in parseable (exact) values')
     parser.add_argument(
         '-r',
         '--recursive',
         action='store_true',
         help='recurse down children caches and print statistics')
     parser.add_argument('-s', metavar="FIELD", help='sort rows by FIELD')
     parser.add_argument('-v',
                         action='store_true',
                         help='Print all statistics')
     #
     # We change the formatter so we can add newlines in the epilog.
     #
     parser.formatter_class = argparse.RawDescriptionHelpFormatter
     parser.epilog = textwrap.fill(
         f"FIELDS := {', '.join(SplKmemCaches.FIELDS.keys())}\n",
         width=80,
         replace_whitespace=False)
     parser.epilog += "\n\n"
     parser.epilog += textwrap.fill(
         ("If -o is not specified the default fields used are "
          f"{', '.join(SplKmemCaches.DEFAULT_FIELDS)}.\n"),
         width=80,
         replace_whitespace=False)
     parser.epilog += "\n\n"
     parser.epilog += textwrap.fill(
         ("If the -s option is not specified and the command's "
          "output is not piped anywhere then we sort by the "
          "following fields in order: "
          f"{', '.join(SplKmemCaches.DEFAULT_SORT_FIELDS)}. "
          "If none of those exists in the field-set we sort by "
          "the first field specified in the set."),
         width=80,
         replace_whitespace=False)
Beispiel #28
0
def main():
    parser = ArgumentParser()
    parser.add_argument("--target", "-t", help="target IP address")
    parser.add_argument("--port", "-p", help="target port number")
    parser.add_argument("--count", "-c", help="number of packets")
    parser.add_argument("--flags", "-f", help="tcp flags")
    parser.add_argument(
        "--version",
        "-v",
        action="version",
        version="Python SynFlood Tool v2.0.1\n@EmreOvunc",
    )
    parser.epilog = "Usage: python3 py3_synflood_cmd.py -t 10.20.30.40 -p 8080 -c 1"

    args = parser.parse_args()

    if args.target is not None:
        if args.port is not None:
            if args.count is None:
                print(
                    "[!]You did not use --counter/-c parameter, so 1 packet will be sent.."
                )
                SYN_Flood(args.target, args.port, 1)

            else:
                SYN_Flood(args.target, args.port, int(args.count), args.flags)

        else:
            print("[-]Please, use --port/-p to give target's port!")
            print("[!]Example: -p 445")
            print("[?] -h for help")
            exit()
    else:
        print(
            """usage: py3_synflood_cmd.py [-h] [--target TARGET] [--port PORT]
                           [--count COUNT] [--version]
optional arguments:
  -h, --help            show this help message and exit
  --target TARGET, -t TARGET
                        target IP address
  --port PORT, -p PORT  target port number
  --count COUNT, -c COUNT
                        number of packets
  --version, -v         show program's version number and exit""")
        exit()
Beispiel #29
0
    def configure(self, parser: ArgumentParser):
        super().configure(parser)
        parser.add_argument('script_name',
                            metavar='SCRIPT_NAME',
                            type=str,
                            help='Script name')
        parser.add_argument(
            '-u',
            '--user',
            type=str,
            default=None,
            help='Container username or UID (format: <name|uid>[:<group|gid>])'
        )
        parser.add_argument('-s',
                            '--session-name',
                            type=str,
                            default=None,
                            help='tmux session name')
        parser.add_argument('-l',
                            '--logging',
                            action='store_true',
                            help='Log the script outputs to a file')
        parser.add_argument(
            '-p',
            '--parameter',
            metavar='PARAMETER=VALUE',
            action='append',
            type=str,
            default=[],
            help=
            'Set a value for the script parameter (format: PARAMETER=VALUE). This '
            'argument can be used multiple times to set several parameters. Parameters can be '
            'used in the script as Mustache variables (for example: {{PARAMETER}}).'
        )
        parser.add_argument(
            '--no-sync',
            action='store_true',
            help='Don\'t sync the project before running the script')

        # add the "double-dash" argument to the usage message
        parser.prog = 'spotty run'
        parser.usage = parser.format_usage()[7:-1] + ' [-- args...]\n'
        parser.epilog = 'The double dash (--) separates custom arguments that you can pass to the script ' \
                        'from the Spotty arguments.'
Beispiel #30
0
def _get_args():
    parser = ArgumentParser(prog='quickgist',
                            description='quickgist is a simple command line '
                            'tool for creating gists.',
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('sources',
                        nargs='*',
                        help='gist content sources, ex: test.txt, '
                        'test1.txt test2.txt, test/*.txt')
    parser.add_argument('-f',
                        type=str,
                        default='',
                        help='gist filename, only used for stdin '
                        'or to override single input filename')
    parser.add_argument('-d', type=str, default='', help='gist description')
    parser.add_argument('-p',
                        default=False,
                        action='store_true',
                        help='private gist')
    parser.add_argument('-l',
                        default=False,
                        action='store_true',
                        help='long url, will not shorten')
    parser.add_argument('-nl',
                        default=False,
                        action='store_true',
                        help='suppress newline after url, good for xclip')
    parser.add_argument('-v',
                        action='version',
                        version='%(prog)s ' + __version__)
    parser.epilog = """Examples:
    $ quickgist file.txt
    $ quickgist -d "some files" file.txt src/*.py
    $ cat foo | quickgist -f foo.txt

Notes:
    Please define an environment variable GIST_TOKEN with your
    GitHub personal access token.

    $ export GIST_TOKEN="YOUR_TOKEN_HERE"
    """

    return parser.parse_args()
Beispiel #31
0
def Func_main():

    parser = ArgumentParser()
    parser.add_argument('--interface', '-in', help='interface de rede')
    parser.add_argument('--alvo', '-a', help='IP alvo')
    parser.add_argument('--porta', '-p', help='Porta alvo')
    parser.add_argument('--pacotes', '-pc', help='Número de pacotes')
    parser.add_argument('--versão',
                        '-v',
                        action='version',
                        version='Python SynFlood 0.1\RamonLean')
    parser.epilog = """Uso: python3 [interface_de_rede] Syn_Flood_Attack.py  [-h] [--alvo ALVO] [--porta PORTA] [--pacotes ] [--versão]
\nUso: python3 wlan0 Syn_Flood_Attack -a 192.168.100.1 -p 80 -pc 10"""
    args = parser.parse_args()

    if args.interface is not None:
        scapy.all.conf.iface = args.interface
        print("Utiliando interface: ", scapy.all.conf.iface)
    else:
        args.interface = scapy.all.conf.iface
        print(
            "Como nenhuma interface foi selecionada, utilizando a interface: ",
            scapy.all.conf.iface)
        time.sleep(2)
    if args.alvo is not None and args.porta is not None:

        if args.pacotes is None:
            print(
                '\nVocê não definiu a quantidade de pacotes, então o ataque continuará até control + c serem pressionadas\n'
            )
            args.pacotes = 0
            time.sleep(2)
            SYN_Flood(args.alvo, args.porta, int(args.pacotes))

        else:
            time.sleep(2)
            SYN_Flood(args.alvo, args.porta, int(args.pacotes))
    else:
        print(Uso_d)
        exit(1)

    exit(0)
def main():
    parser = ArgumentParser()
    parser.add_argument('--target', '-t', help='target IP address')
    parser.add_argument('--port', '-p', help='target port number')
    parser.add_argument('--count', '-c', help='number of packets')
    parser.add_argument('--version',
                        '-v',
                        action='version',
                        version='Python SynFlood Tool v2.0.1\n@EmreOvunc')
    parser.epilog = "Usage: python3 py3_synflood_cmd.py -t 10.20.30.40 -p 8080 -c 1"

    args = parser.parse_args()

    if args.target is not None:
        if args.port is not None:
            if args.count is None:
                print(
                    '[!]You did not use --counter/-c parameter, so 1 packet will be sent..'
                )
                SYN_Flood(args.target, args.port, 1)

            else:
                SYN_Flood(args.target, args.port, int(args.count))

        else:
            print('[-]Please, use --port/-p to give target\'s port!')
            print('[!]Example: -p 445')
            print('[?] -h for help')
            exit()
    else:
        print(
            '''usage: py3_synflood_cmd.py [-h] [--target TARGET] [--port PORT]
                           [--count COUNT] [--version]
optional arguments:
  -h, --help            show this help message and exit
  --target TARGET, -t TARGET
                        target IP address
  --port PORT, -p PORT  target port number
  --count COUNT, -c COUNT
                        number of packets
  --version, -v         show program's version number and exit''')
        exit()
Beispiel #33
0
    def get_parser(self):
        p = ArgumentParser(self.description)
        p.formatter_class = argparse.RawDescriptionHelpFormatter
        p.add_argument('-a',
                       '--all',
                       action='store_true',
                       default=False,
                       help="Display all images")
        p.add_argument('-l',
                       '--long',
                       action='store_true',
                       default=False,
                       help='Display extra information for each image')
        p.add_argument('--sharedwith',
                       action='store_true',
                       default=False,
                       help='modifier flag.  See epilog for examples.')
        g = p.add_mutually_exclusive_group()
        g.add_argument('-u', '--user', help='List images owned by USER')
        g.add_argument('-g', '--group', help="List images shared with GROUP.")
        p.epilog = """\
Example Usages:

    repoman list
        list the current users images

    repoman list --sharedwith
        list all images shared with the current user

    repoman list --user bob
        list all images owned by the user 'bob'

    repoman list --sharedwith --user bob
        list all images shared with the user 'bob'

    repoman list --group babar
        list all images accessible by members of the 'babar' group

    repoman list --sharedwith --group babar
        has the same effect as the previous example."""

        return p
Beispiel #34
0
def parse_cems_download_args(p: ArgumentParser):
    p.description = 'Downlowd continuous emissions data from the US EPA FTP server'
    p.add_argument('time_res',
                   choices=('daily', 'hourly'),
                   help='Which time resolution of data to download')
    p.add_argument(
        'start_time',
        help='Beginning of time period to download, in YYYY-MM-DD format.')
    p.add_argument(
        'stop_time',
        help='End of time period to download, in YYYY-MM-DD format.')
    p.add_argument(
        '-s',
        '--save-dir',
        default='.',
        help=
        'Where to save the downloaded files. Default is the current directory.'
    )
    p.add_argument(
        '-c',
        '--no-decompress',
        action='store_false',
        dest='unzip',
        help=
        'By default the .zip files downloaded are unzipped into their .csv file. Pass this flag to '
        'skip that and leave them as .zip files.')
    p.add_argument(
        '-k',
        '--keep-zip',
        action='store_false',
        dest='delete_zip',
        help=
        'If the .zip files are decompresses, they are by default deleted. Pass this flag to skip '
        'deleting them. This has no effect either way if --no-decompress is set.'
    )
    p.set_defaults(driver_fxn=download_cl_driver)
    p.epilog = 'A note on the start and stop time: the hourly data is provided in monthly files and the daily data ' \
               'in quarterly files. The start/stop time given filter based on the first date of the files. That is, ' \
               'if you specify a start date of 15 Jan 2020 and an end date of 15 Feb 2020 for the hourly data, the ' \
               'file for February will be downloaded because 15 Jan <= 1 Feb <= 15 Feb, but the file for January will ' \
               'NOT be downloaded.'
Beispiel #35
0
    def _configure_args(self, parser: ArgumentParser) -> ArgumentParser:
        # Description of the sub program
        parser.description = "A parallel implementation of the full pipeline of translation from texts to vectors " \
                             "of semantic complexity."
        parser.epilog = """For each text file processed in parallel, the pipeline first clean and split text in paragraphs, 
and identify the DBpedia entity with the use of a Spotlight REST Api. Each entity is then enrich with its types by 
queriyng a DBpedia SPARQL endpoint. Each list of entities (for each document) is then processed in parallel to compute
a graph of concept, conposed of the entities, their types and the hierachy of ontology classes that define these types.
Finally each graph is vectorized in parallel. Note that three ontologies are used so far: Schema, DBpedia ontology and
Yago. The result csv file is composed one line per fil, each of them being composed of the file name (without its
extension) and the several complexity features."""

        # Positionnal arguments
        parser.add_argument('data_in_dir', help='Texts input directory', metavar='<Texts Directory>',
                            type=str)
        parser.add_argument('out_file', help='output CSV file of vectors', metavar='<Output file>', type=str)
        parser.add_argument('spotlight_ep', help='DBpedia spotlight endpoint '
                                                 '(ex.: "https://api.dbpedia-spotlight.org/en/annotate")',
                            metavar='<Spotlight Endpoint>', type=str)
        # Optional arguments
        parser.add_argument('-nc', '--num-cores', help='Number of cores to use for parallel processing (default: 1)',
                            type=int, default=1)
        parser.add_argument('-ei', '--ext-in', help='Extension of input files (default: ".txt")',
                            type=str, default='.txt')
        parser.add_argument('-co', '--confidence', help='Confidence of the DBpedia spotlight service (default: 0.5).',
                            type=float, default=0.5)
        parser.add_argument('--sparql-ep', help='SPARQL endpoint (default: "http://dbpedia.org/sparql")',
                            type=str, default='http://dbpedia.org/sparql')
        parser.add_argument('--max-concepts', help='Max concepts per SPARQL query (default: 100)',
                            type=int, default=100)
        parser.add_argument('--nice-server', help='Be nice to the SPARQL server by waiting randomly from 0 to 1 '
                                                  'second between each request (disabled by default, but recommended)',
                            action='store_false')
        parser.add_argument('--save-info',
                            help='Save the entity-fino mapping dictionnary to a json file (default: No)',
                            metavar='<Json File>', type=str, default=None)
        parser.add_argument('-on', '--ontology', help='Ontologies to used (Default: all)', type=str, action='append',
                            choices=DefaultOntologies.available_ontologies().keys(), default=[])
        parser.add_argument('--save-graphs', help='Save the several graphs as json files into a directory',
                            metavar='<Graphs Directory>', type=str, default=None)
        return parser
Beispiel #36
0
def add_arguments(parser: argparse.ArgumentParser) -> None:
    """Adds arguments to command line parser
    Parameters:
        parser: parser instance to add arguments to
    """
    parser.add_argument('--merge_csv', action='store_true', default=False,
                        help='merge same-name CSV files into one file of the same name (default=False)')
    parser.add_argument('--csv_header_lines', nargs='?', default=0,
                        help='expected number of header lines in any CSV file when merging CSV files (default=0)')
    parser.add_argument('--maps', nargs='?', type=str,
                        help='one or more comma separated folder mappings of <source path>:<destination path>')
    parser.add_argument('--extra_files', nargs='?', type=str,
                        help='one or more colon separated files to copy <file 1>:<file 2>:...')
    parser.add_argument('results_file', metavar='<results>', type=str,
                        help='the path to the results file to act upon')
    parser.add_argument('cache_folder', metavar='<cache>', type=str,
                        help='the path to cache the results into')

    parser.epilog = 'Mappings are exact character matches from the start of file paths; no checks are made to ensure complete' +\
                    ' folder names are matched. For example, a mapping of "/home/tom:/home/sue" will map the path "/home/tomorrow"' +\
                    ' to "/home/sueorrow".'
Beispiel #37
0
 def _init_argparse(self, parser: argparse.ArgumentParser) -> None:
     parser.add_argument(
         "-a",
         "--all",
         action="store_true",
         help="list all threads for each unique stack trace" +
         " instead of printing a single representative thread")
     parser.add_argument(
         "-c",
         "--function",
         help="only print threads whose stacks contains FUNCTION")
     parser.add_argument(
         "-m",
         "--module",
         help="only print threads whose stacks contain functions from MODULE"
     )
     parser.add_argument(
         "-t",
         "--tstate",
         help="only print threads which are in TSTATE thread state")
     parser.epilog = "TSTATE := [{:s}]".format(", ".join(
         Stacks.TASK_STATES.values()))
Beispiel #38
0
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    parser = ArgumentParser(
        formatter_class=RawDescriptionHelpFormatter)
    subparsers = parser.add_subparsers(dest='commands',
                                       title='Available commands')

    lst = add_commands(subparsers, globals())
    if HAS_BOTO:
        lst += add_commands(subparsers, create_ami)
    lst += add_commands(subparsers, tkl_commands)
    lst += add_commands(subparsers, install)

    parser.epilog = '\n'.join(['  {:21} {}'.format(x, y) for x, y in lst])
    if not HAS_BOTO:
        parser.epilog += '\n\nNOTE: AMI commands are disabled because the ' + \
                         'Python Boto module is not installed.'
    parser.add_argument(
        '-v',
        '--verbose',
        action='store_true',
        help='Turn on debug output')

    if len(argv) < 1:
        argv.append('--help')
    args = parser.parse_args(argv)

    # Init log
    loglevel = boto_loglevel = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=loglevel)
    logging.getLogger('boto').setLevel(boto_loglevel)

    # Run command
    ok = args.func(args)
    return 0 if ok else 1
Beispiel #39
0
                os.rename(ring, os.path.join(_tests, 'generated-keys'))


if __name__ == "__main__":

    before_run()

    suite_names = list()
    for name, methodset in suites.items():
        suite_names.append(name)
        setattr(GPGTestCase, name, list(methodset))

    parser = ArgumentParser(description="Unittests for python-gnupg")
    parser.add_argument('--doctest', dest='run_doctest',
                        type=bool, default=False,
                        help='Run example code in docstrings')
    parser.add_argument('--quiet', dest='quiet',
                        type=bool, default=False,
                        help='Disable logging to stdout')
    parser.add_argument('--verbose', dest='verbose',
                        type=int, default=4,
                        help='Set verbosity level (low=1 high=5) (default: 4)')
    parser.add_argument('test', metavar='test', nargs='+', type=str,
                        help='Select a test suite to run (default: all)')
    parser.epilog = "Available test suites: %s" % " ".join(suite_names)

    args = parser.parse_args()
    args.suites = suites

    sys.exit(main(args))
Beispiel #40
0
 def get_parser(self):
     p = ArgumentParser(self.description)
     p.usage = "create-group [-h] [--metadata value [--metadata value ...]]"
     p.epilog = "See documentation for a list of required and optional metadata"
     return p
Beispiel #41
0
def main():
    """
    Run the evennia launcher main program.

    """

    # set up argument parser

    parser = ArgumentParser(description=CMDLINE_HELP)
    parser.add_argument(
        '-v', '--version', action='store_true',
        dest='show_version', default=False,
        help="Show version info.")
    parser.add_argument(
        '-i', '--interactive', action='store_true',
        dest='interactive', default=False,
        help="Start given processes in interactive mode.")
    parser.add_argument(
        '-l', '--log', action='store_true',
        dest="logserver", default=False,
        help="Log Server data to log file.")
    parser.add_argument(
        '--init', action='store', dest="init", metavar="name",
        help="Creates a new game directory 'name' at the current location.")
    parser.add_argument(
        '--list', nargs='+', action='store', dest='listsetting', metavar="key",
        help=("List values for server settings. Use 'all' to list all "
              "available keys."))
    parser.add_argument(
        '--profiler', action='store_true', dest='profiler', default=False,
        help="Start given server component under the Python profiler.")
    parser.add_argument(
        '--dummyrunner', nargs=1, action='store', dest='dummyrunner',
        metavar="N",
        help="Test a running server by connecting N dummy accounts to it.")
    parser.add_argument(
        '--settings', nargs=1, action='store', dest='altsettings',
        default=None, metavar="filename.py",
        help=("Start evennia with alternative settings file from "
              "gamedir/server/conf/. (default is settings.py)"))
    parser.add_argument(
        '--initsettings', action='store_true', dest="initsettings",
        default=False,
        help="Create a new, empty settings file as gamedir/server/conf/settings.py.")
    parser.add_argument(
        '--external-runner', action='store_true', dest="doexit",
        default=False,
        help="Handle server restart with an external process manager.")
    parser.add_argument(
        "operation", nargs='?', default="noop",
        help="Operation to perform: 'start', 'stop', 'reload' or 'menu'.")
    parser.add_argument(
        "service", metavar="component", nargs='?', default="all",
        help=("Which component to operate on: "
              "'server', 'portal' or 'all' (default if not set)."))
    parser.epilog = (
        "Common usage: evennia start|stop|reload. Django-admin database commands:"
        "evennia migration|flush|shell|dbshell (see the django documentation for more django-admin commands.)")

    args, unknown_args = parser.parse_known_args()

    # handle arguments
    option, service = args.operation, args.service

    # make sure we have everything
    check_main_evennia_dependencies()

    if not args:
        # show help pane
        print(CMDLINE_HELP)
        sys.exit()
    elif args.init:
        # initialization of game directory
        create_game_directory(args.init)
        print(CREATED_NEW_GAMEDIR.format(
            gamedir=args.init,
            settings_path=os.path.join(args.init, SETTINGS_PATH)))
        sys.exit()

    if args.show_version:
        # show the version info
        print(show_version_info(option == "help"))
        sys.exit()

    if args.altsettings:
        # use alternative settings file
        sfile = args.altsettings[0]
        global SETTINGSFILE, SETTINGS_DOTPATH, ENFORCED_SETTING
        SETTINGSFILE = sfile
        ENFORCED_SETTING = True
        SETTINGS_DOTPATH = "server.conf.%s" % sfile.rstrip(".py")
        print("Using settings file '%s' (%s)." % (
            SETTINGSFILE, SETTINGS_DOTPATH))

    if args.initsettings:
        # create new settings file
        global GAMEDIR
        GAMEDIR = os.getcwd()
        try:
            create_settings_file(init=False)
            print(RECREATED_SETTINGS)
        except IOError:
            print(ERROR_INITSETTINGS)
        sys.exit()

    if args.dummyrunner:
        # launch the dummy runner
        init_game_directory(CURRENT_DIR, check_db=True)
        run_dummyrunner(args.dummyrunner[0])
    elif args.listsetting:
        # display all current server settings
        init_game_directory(CURRENT_DIR, check_db=False)
        list_settings(args.listsetting)
    elif option == 'menu':
        # launch menu for operation
        init_game_directory(CURRENT_DIR, check_db=True)
        run_menu()
    elif option in ('start', 'reload', 'stop'):
        # operate the server directly
        init_game_directory(CURRENT_DIR, check_db=True)
        server_operation(option, service, args.interactive, args.profiler, args.logserver, doexit=args.doexit)
    elif option != "noop":
        # pass-through to django manager
        check_db = False
        if option in ('runserver', 'testserver'):
            print(WARNING_RUNSERVER)
        if option in ("shell", "check"):
            # some django commands requires the database to exist,
            # or evennia._init to have run before they work right.
            check_db = True
        if option == "test":
            global TEST_MODE
            TEST_MODE = True
        init_game_directory(CURRENT_DIR, check_db=check_db)

        args = [option]
        kwargs = {}
        if service not in ("all", "server", "portal"):
            args.append(service)
        if unknown_args:
            for arg in unknown_args:
                if arg.startswith("--"):
                    print("arg:", arg)
                    if "=" in arg:
                        arg, value = [p.strip() for p in arg.split("=", 1)]
                    else:
                        value = True
                    kwargs[arg.lstrip("--")] = value
                else:
                    args.append(arg)
        try:
            django.core.management.call_command(*args, **kwargs)
        except django.core.management.base.CommandError as exc:
            args = ", ".join(args)
            kwargs = ", ".join(["--%s" % kw for kw in kwargs])
            print(ERROR_INPUT.format(traceback=exc, args=args, kwargs=kwargs))
    else:
        # no input; print evennia info
        print(ABOUT_INFO)
Beispiel #42
0
 def get_parser(self):
     p = ArgumentParser(self.description)
     p.usage = "create-image [-h] [-f FILE] [--metadata value [--metadata value ...]]"
     p.epilog = "See documentation for a list of required and optional metadata"
     p.add_argument('-f', '--file', help='Image file to upload')
     return p
Beispiel #43
0
def main():
    """
    Run the muddery main program.
    """

    # set up argument parser

    parser = ArgumentParser(description=CMDLINE_HELP)
    parser.add_argument('-v', '--version', action='store_true',
                        dest='show_version', default=False,
                        help="Show version info.")
    parser.add_argument('-i', '--interactive', action='store_true',
                        dest='interactive', default=False,
                        help="Start given processes in interactive mode.")
    parser.add_argument('--init', action='store', dest="init", metavar="game_name [template]",
                        help="Creates a new game directory 'game_name' at the current location (from optional template).")
    parser.add_argument('-l', nargs='+', action='store', dest='listsetting', metavar="key",
                        help="List values for server settings. Use 'all' to list all available keys.")
    parser.add_argument('--profiler', action='store_true', dest='profiler', default=False,
                        help="Start given server component under the Python profiler.")
    parser.add_argument('--dummyrunner', nargs=1, action='store', dest='dummyrunner', metavar="N",
                        help="Tests a running server by connecting N dummy players to it.")
    parser.add_argument('--settings', nargs=1, action='store', dest='altsettings', default=None, metavar="filename.py",
                        help="Start evennia with alternative settings file in gamedir/server/conf/.")
    parser.add_argument("option", nargs='?', default="noop",
                        help="Operational mode: 'start', 'stop' or 'restart'.")
    parser.add_argument("service", metavar="component", nargs='?', default="all",
                        help="Server component to operate on: 'server', 'portal' or 'all' (default).")
    parser.epilog = "Example django-admin commands: 'migrate', 'flush', 'shell' and 'dbshell'. " \
                    "See the django documentation for more django-admin commands."

    args, unknown_args = parser.parse_known_args()

    # handle arguments
    option, service = args.option, args.service

    # make sure we have everything
    evennia_launcher.check_main_evennia_dependencies()

    if not args:
        # show help pane
        print(CMDLINE_HELP)
        sys.exit()
    elif args.init:
        # initialization of game directory
        if option == "noop":
            option = ""
        create_game_directory(args.init, option)

        evennia_launcher.init_game_directory(GAMEDIR, check_db=False)

        try:
            django_args = ["makemigrations"]
            django_kwargs = {}
            django.core.management.call_command(*django_args, **django_kwargs)
        except django.core.management.base.CommandError, exc:
            print(ERROR_INPUT.format(traceback=exc, args=django_args, kwargs=django_kwargs))

        try:
            django_args = ["migrate"]
            django_kwargs = {}
            django.core.management.call_command(*django_args, **django_kwargs)
        except django.core.management.base.CommandError, exc:
            print(ERROR_INPUT.format(traceback=exc, args=django_args, kwargs=django_kwargs))
Beispiel #44
0
parser.add_argument("--no-autofuncs", dest = "add_default_funcs", action="store_false", default = True, help = "disable use of automatically identified functions.")

parser.add_argument("-k", "--keywords", dest = "keywords", type=str, default = 'hv,PROD,EMISSION', help = "List of keywords to be ignored in reactants or products (comma delimited; default='hv')")

parser.add_argument("-o", "--outpath", dest = "outpath", type=str, default = None, help = "Output path.")

parser.add_argument("-m", "--monitor", dest = "monitor", type=str, default = None, help = "Extra monitor values (comma separated string).")

parser.add_argument("-s", "--solver", dest = "solver", default = None, help = "solver (default: lsoda; vode; zvode; dopri5; dop853) with optional keywords comma delimited (e.g., lsoda,atol=1e-2,rtol=1e-5,max_order_s=2,max_order_ns=2,nsteps=1000)")

parser.add_argument("-c", "--code", dest = "code", default = "", help = "code to solve (exec) after model is compiled and run (unless --norun); out is a keyword for the mechanism that has been generated")

parser.epilog = """

functions for world updating can be explored using pydoc pykpp.updaters

functions for reaction rates and world updating can be explored using pydoc pykpp.stdfuncs

run existing models (pykpp modelfile.kpp):\n\t""" + '\n\t'.join(modelpaths)
def main(globals = {}):
    options = parser.parse_args()

    if len(options.paths) == 0:
        parser.print_help()
        exit()
    
    outs = []
    for arg in options.paths:
        out = Mech(arg, verbose = options.verbose, keywords = [k_.strip() for k_ in options.keywords.split(',')], add_default_funcs = options.add_default_funcs)
        if options.monitor is not None:
            out.monitor = tuple([(None if k not in out.allspcs else out.allspcs.index(k), k) for k in options.monitor.split(',')]) + out.monitor

if __name__ == "__main__":

	if sys.version_info[0] == 2 and sys.version_info[1] < 7:
		sys.stderr.write("Python versions below 2.7 are not supported.\n")
		sys.stderr.write("Your Python version:\n")
		sys.stderr.write(".".join([str(v) for v in sys.version_info[:3]]) + "\n")
		sys.exit(0)

	from argparse import ArgumentParser, RawDescriptionHelpFormatter

	parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter)
	parser.prog = "Coptic NLP Pipeline"
	parser.usage = "python coptic_nlp.py [OPTIONS] files"
	parser.epilog = """Example usage:
--------------
Add norm, lemma, parse, tag, unary tags, find multiword expressions and do language recognition:
> python coptic_nlp.py -penmult infile.txt        

Just tokenize a file using pipes and dashes:
> python coptic_nlp.py -o pipes infile.txt       

Tokenize with pipes and mark up line breaks, conservatively detokenize bound groups, assume seg boundary at merge site:
> python coptic_nlp.py -b -d 1 --segment_merged -o pipes infile.txt

Normalize, tag, lemmatize, find multiword expressions and parse, splitting sentences by <verse> tags:
> python coptic_nlp.py -pnltm -s verse infile.txt       

Add full analyses to a whole directory of *.xml files, output to a specified directory:    
> python coptic_nlp.py -penmult --dirout /home/cop/out/ *.xml
def main():
    """
    Run the evennia launcher main program.

    """

    # set up argument parser

    parser = ArgumentParser(description=CMDLINE_HELP)
    parser.add_argument(
        '-v', '--version', action='store_true',
        dest='show_version', default=False,
        help="Show version info.")
    parser.add_argument(
        '-i', '--interactive', action='store_true',
        dest='interactive', default=False,
        help="Start given processes in interactive mode.")
    parser.add_argument(
        '-l', '--log', action='store_true',
        dest="logserver", default=False,
        help="Log Server data to log file.")
    parser.add_argument(
        '--init', action='store', dest="init", metavar="name",
        help="Creates a new game directory 'name' at the current location.")
    parser.add_argument(
        '--list', nargs='+', action='store', dest='listsetting', metavar="key",
        help=("List values for server settings. Use 'all' to list all "
              "available keys."))
    parser.add_argument(
        '--profiler', action='store_true', dest='profiler', default=False,
        help="Start given server component under the Python profiler.")
    parser.add_argument(
        '--dummyrunner', nargs=1, action='store', dest='dummyrunner',
        metavar="N",
        help="Tests a running server by connecting N dummy players to it.")
    parser.add_argument(
        '--settings', nargs=1, action='store', dest='altsettings',
        default=None, metavar="filename.py",
        help=("Start evennia with alternative settings file in "
              "gamedir/server/conf/."))
    parser.add_argument(
        "option", nargs='?', default="noop",
        help="Operational mode: 'start', 'stop', 'restart' or 'menu'.")
    parser.add_argument(
        "service", metavar="component", nargs='?', default="all",
        help=("Server component to operate on: "
              "'server', 'portal' or 'all' (default)."))
    parser.epilog = (
        "Example django-admin commands: "
        "'migrate', 'flush', 'shell' and 'dbshell'. "
        "See the django documentation for more django-admin commands.")

    args, unknown_args = parser.parse_known_args()

    # handle arguments
    option, service = args.option, args.service

    # make sure we have everything
    check_main_evennia_dependencies()

    if not args:
        # show help pane
        print CMDLINE_HELP
        sys.exit()
    elif args.init:
        # initialization of game directory
        create_game_directory(args.init)
        print CREATED_NEW_GAMEDIR.format(
            gamedir=args.init,
            settings_path=os.path.join(args.init, SETTINGS_PATH))
        sys.exit()

    if args.show_version:
        # show the version info
        print show_version_info(option == "help")
        sys.exit()

    if args.altsettings:
        # use alternative settings file
        sfile = args.altsettings[0]
        global SETTINGSFILE, SETTINGS_DOTPATH
        SETTINGSFILE = sfile
        SETTINGS_DOTPATH = "server.conf.%s" % sfile.rstrip(".py")
        print "Using settings file '%s' (%s)." % (
            SETTINGSFILE, SETTINGS_DOTPATH)

    if args.dummyrunner:
        # launch the dummy runner
        init_game_directory(CURRENT_DIR, check_db=True)
        run_dummyrunner(args.dummyrunner[0])
    elif args.listsetting:
        # display all current server settings
        init_game_directory(CURRENT_DIR, check_db=False)
        list_settings(args.listsetting)
    elif option == 'menu':
        # launch menu for operation
        init_game_directory(CURRENT_DIR, check_db=True)
        run_menu()
    elif option in ('start', 'reload', 'stop'):
        # operate the server directly
        init_game_directory(CURRENT_DIR, check_db=True)
        server_operation(option, service, args.interactive, args.profiler, args.logserver)
    elif option != "noop":
        # pass-through to django manager
        check_db = False
        if option in ('runserver', 'testserver'):
            print WARNING_RUNSERVER
        if option == "shell":
            # to use the shell we need to initialize it first,
            # and this only works if the database is set up
            check_db = True
        init_game_directory(CURRENT_DIR, check_db=check_db)

        args = [option]
        kwargs = {}
        if service not in ("all", "server", "portal"):
            args.append(service)
        if unknown_args:
            for arg in unknown_args:
                if arg.startswith("--"):
                    print "arg:", arg
                    if "=" in arg:
                        arg, value = [p.strip() for p in arg.split("=", 1)]
                    else:
                        value = True
                    kwargs[arg.lstrip("--")] = [value]
                else:
                    args.append(arg)
        try:
            django.core.management.call_command(*args, **kwargs)
        except django.core.management.base.CommandError, exc:
            args = ", ".join(args)
            kwargs = ", ".join(["--%s" % kw for kw in kwargs])
            print ERROR_INPUT.format(traceback=exc, args=args, kwargs=kwargs)
Beispiel #47
0
def main(args=None):
    optparser = ArgumentParser(description='s3tos3backup is a tool for managing backups for Amazon S3 storage with IAM role support.')
    preferred_encoding = locale.getpreferredencoding() or "UTF-8"
    optparser.set_defaults(encoding=preferred_encoding)
    config_file = os.path.join(os.getenv("HOME"), ".s3tos3backup")
    optparser.set_defaults(config=config_file)
    optparser.set_defaults(verbosity=default_verbosity)

    optparser.add_argument("-c", "--config", dest="config", metavar="FILE",
                           help="Config file name. Defaults to %s" % config_file)
    optparser.add_argument("--access_key", dest="aws_access_key", help="AWS Access Key")
    optparser.add_argument("--secret_key", dest="aws_secret_key", help="AWS Secret Key")
    optparser.add_argument("-b", "--bucket", dest="bucket_name", help="Bucket name")
    optparser.add_argument("-o", "--remove-older-days", dest="remove_older_days",
                           help="Remove backups older than days")
    optparser.add_argument("-v", "--verbose", dest="verbosity", action="store_const", const=logging.INFO,
                           help="Enable verbose output")
    optparser.add_argument("-d", "--debug", dest="verbosity", action="store_const", const=logging.DEBUG,
                           help="Enable debug output")
    optparser.add_argument("--remove-only", dest="backup", action="store_false", default=True,
                           help="Remove only old backups. Do not do a backup")
    optparser.add_argument("--backup-only", dest="remove", action="store_false", default=True,
                           help="Do a backup. Do not remove only old backups")
    optparser.add_argument("--configure", dest="configure", action="store_true",
                           help="Save configuration and exit")
    optparser.add_argument("--version", dest="show_version", action="store_true",
                           help="Show s3tos3backup version (%s) and exit" % (PkgInfo.version))

    optparser.epilog = ("\nFor more information see the project homepage:\n%s\n" % PkgInfo.url)

    options = optparser.parse_args(args)

    logging.basicConfig(level=options.verbosity,
                        format='%(levelname)s: %(message)s',
                        stream=sys.stderr)

    if options.show_version:
        output(u"s3tos3backup version %s" % PkgInfo.version)
        sys.exit(0)

    if options.configure:
        with open(config_file, 'w') as f:
            f.write(CONFIG_TEMPLATE % dict(access_key=options.aws_access_key,
                                           secret_key=options.aws_secret_key,
                                           bucket_name=options.bucket_name,
                                           remove_older_days=options.remove_older_days))
        output(u"Config saved to: %s" % config_file)
        sys.exit(0)

    if not options.config:
        logging.error(u"Can't find a config file. Please use --config option.")
        sys.exit(1)

    logging.root.setLevel(options.verbosity)

    config = ConfigParser.SafeConfigParser({'bucket_name': options.bucket_name,
                                            'aws_key': options.aws_access_key,
                                            'aws_secret_key': options.aws_secret_key,
                                            'remove_older_days': options.remove_older_days or '7'})
    if os.path.exists(options.config):
        config.read(options.config)

    if not config.has_section('main'):
        config.add_section('main')

    bucket_name = config.get('main', 'bucket_name')
    try:
        aws_key = config.get('main', 'access_key')
        aws_secret_key = config.get('main', 'secret_key')
    except ConfigParser.NoOptionError:
        aws_key = None
        aws_secret_key = None
    remove_older_days = config.getint('main', 'remove_older_days')

    if not bucket_name:
        logging.error(u"Bucket name is required. Please use --bucket option.")
        sys.exit(1)

    try:
        run_backup(bucket_name, options.backup, options.remove, aws_key, aws_secret_key, remove_older_days)
    except Exception, e:
        report_exception(e)
        sys.exit(1)
Beispiel #48
0
 def get_parser(self):
     p = ArgumentParser(self.description)
     p.usage = "modify-image [-h] image [--metadata value [--metadata value ...]]"
     p.epilog = "See documentation for a list of required and optional metadata"
     p.add_argument('image', help='The existing image you want to modify')
     return p
Beispiel #49
0
parser.add_argument("--no-jacobian", dest = "jacobian", action="store_false", default = True, help = "disable use of jacobian")

parser.add_argument("--no-autofuncs", dest = "add_default_funcs", action="store_false", default = True, help = "disable use of automatically identified functions.")

parser.add_argument("-k", "--keywords", dest = "keywords", type=str, default = 'hv,PROD,EMISSION', help = "List of keywords to be ignored in reactants or products (comma delimited; default='hv')")

parser.add_argument("-o", "--outpath", dest = "outpath", type=str, default = None, help = "Output path.")

parser.add_argument("-m", "--monitor", dest = "monitor", type=str, default = None, help = "Extra monitor values (comma separated string).")

parser.add_argument("-s", "--solver", dest = "solver", default = None, help = "solver (default: lsoda; vode; zvode; dopri5; dop853) with optional keywords comma delimited (e.g., lsoda,atol=1e-2,rtol=1e-5,max_order_s=2,max_order_ns=2,nsteps=1000)")

parser.add_argument("-c", "--code", dest = "code", default = "", help = "code to solve (exec) after model is compiled and run (unless --norun); out is a keyword for the mechanism that has been generated")

parser.epilog = """

functions for world updating can be explored using pydoc pykpp.updaters

functions for reaction rates and world updating can be explored using pydoc pykpp.stdfuncs
"""
def main(globals = {}):
    options = parser.parse_args()

    if len(options.paths) == 0:
        parser.print_help()
        exit()
    
    outs = []
    for arg in options.paths:
        out = Mech(arg, verbose = options.verbose, keywords = [k_.strip() for k_ in options.keywords.split(',')], add_default_funcs = options.add_default_funcs)
Beispiel #50
0
	
	if cmd and port:
		def prompt():
			port.write(cmd)
			incoming = fmt(port.readline()).strip()
			return raw_input(incoming + pstr())
	else:
		prompt = lambda: raw_input(pstr())
	return prompt

### Setup commandline arguments ###

parser = ArgumentParser()
parser.usage = "%(prog)s device [command, ...] [options]"
parser.description = "A dumb serial terminal"
parser.epilog = """This 'terminal' waits for user input, sends it and prints any replies.
To fetch possible responses without sending anything just hit return.
Use CTRL-D or CTRL-C to quit."""

parser.add_argument("device", help="serial device to open")
parser.add_argument("commands", nargs='*', help="send commands and exit after response")

parser.add_argument("-v", "--version", action="version", version="%(prog)s "+__version__)
parser.add_argument("-q", "--quiet", action="store_true", help="don't print responses to stdout")
parser.add_argument("--baudrate", metavar="BAUD", default=115200, type=int, help="set baudrate (115200)")
parser.add_argument("--timeout", metavar="SEC", default=0.5, type=float, help="set read timeout (0.5)")
parser.add_argument("--logfile", metavar="FILE", type=FileType(mode="w"), help="log everything to FILE")
parser.add_argument("--eol", default="lf", choices=["lf", "crlf", "cr", "lfcr", "none"], help="choose end of line characters (lf)")

group = parser.add_argument_group("Format")
group.add_argument("--hex", dest="converter", action="store_const", const=hexs, default=None)
Beispiel #51
0
def getparser(has_ofile, plot_options = False, interactive = False):
    """getparser produces a parser for PseudoNetCDF
    
Parameters
----------
has_ofile : boolean
            Requires the outpath option and processes existence check
plot_options : boolean, optional
               Adds options for plotting including matplotlibrc, spatial
               overlays, and normalization options, default is False
interactive : boolean, optional
              Adds for interactive option, default is False
         
Returns
-------
parser : ArgumentParser with options that are processable with pncparse

    """
    from PseudoNetCDF.register import readers
    parser = ArgumentParser(description = """PseudoNetCDF Argument Parsing


""", formatter_class=RawDescriptionHelpFormatter)
    parser.epilog = """
Detailed Steps
--------------

PseudoNetCDF has many operations and the order often matters. The order is consistent with the order of options in the formatted help. The default order is summarized as:

1. Open with specified reader (-f)
2. Select subset of variables (-v)
2. Add attributes (-a)
4. Apply masks (--mask)
5. Add conventions to support later operations (--to-convention, --from-convention)
6. Combine files via stacking on dimensions (--stack)
7. Slice dimensions (-s --slice)
8. Reduce dimensions (-r --reduce)
9. Convolve dimensions (-c)
10. Extract specific coordinates (--extract)
11. Remove singleton dimensions (--remove-singleton)
12. Apply expressions (--expr then --exprscripts)
13. Apply binary operators (--op_typ)

To impose your own order, use standard options (global options) and then use -- to force positional interpretation of remaining options. In remaining options, use --sep to separate groups of files and options to be evaluated before any global operations."""
    parser.add_argument('ifile', nargs='+', help='path to a file formatted as type -f')
    
    parser.add_argument("-f", "--format", dest = "format", default = 'netcdf', metavar = '{' + ', '.join(_readernames) + '}', help = "File format (default netcdf), can be one of the choices listed, or an expression that evaluates to a reader. Keyword arguments are passed via ,kwd=value.")

    parser.add_argument("--help-format", dest = "helpformat", default = None, help = "Show help for file format (must be one of the options for -f)")
    
    parser.add_argument("--sep", dest = "separator", default = None, help = "Used to separate groups of arguments for parsing (e.g., pncgen -- [options1] file(s)1 [--sep [options2] file(s)2 [... [--sep [optionsN] file(s)N]] ")

    parser.add_argument("--inherit", dest="inherit", action = "store_true", default=False, help = "Allow subparsed sections (separated with -- and --sep) to inherit from global options (-f, --format is always inherited).")

    parser.add_argument("--mangle", dest = "mangle", action = "store_true", default = False, help = "Remove non-standard ascii from names")
    
    parser.add_argument("--remove-singleton", dest = "removesingleton", type = lambda x: [k for k in x.split() if k != ''], default = False, help = "Remove singleton (length 1) dimensions")
    
    # Only has output file if pncgen is called.
    if has_ofile:
        parser.add_argument("-O", "--clobber", dest = "clobber", action = 'store_true', default = False, help = "Overwrite existing file if necessary.")

        parser.add_argument("--out-format", dest = "outformat", default = "NETCDF3_CLASSIC", help = "File output format (e.g., NETCDF3_CLASSIC, NETCDF4_CLASSIC, NETCDF4;pncgen only)", type = str, choices = 'NETCDF3_CLASSIC NETCDF4_CLASSIC NETCDF4'.split() + _writernames)

        parser.add_argument("--mode", dest = "mode", type = str, default = "w", help = "File mode for writing (w, a or r+ or with unbuffered writes ws, as, or r+s; pncgen only).", choices = 'w a r+ ws as r+s'.split())

        parser.add_argument("--verbose", dest="verbose", action = "store_true", default=False, help = "Provides verbosity with pncgen")

        parser.add_argument('outpath', type = str, help='path to a output file formatted as --out-format')

    else:
        parser.add_argument("-H", "--header", dest="header", action = "store_true", default=False)
        
        parser.add_argument("-t", "--timestring", dest="timestring", action = "store_true", default=False)
        
        parser.add_argument("--full-indices", dest="full_indices",default=None, metavar = "[c|f]", choices = ['c', 'f'])

        parser.add_argument("-l", "--length", dest="line_length", type = int, default=80, metavar = "LEN", help = "CDL line length (pncdump only)")

        parser.add_argument("--float-precision", dest="float_precision", type = int, default=8, metavar = "FDIG", help = "single precision digitis (default 8; pncdump only)")

        parser.add_argument("--double-precision", dest="double_precision", type = int, default=16, metavar = "PDIG", help = "pdig double precision digits (default 16; pncdump only)")

    parser.add_argument("--dump-name", dest = "cdlname", type = str, default = None, help = "Name for display in ncdump")

    parser.add_argument("--coordkeys", dest = "coordkeys", type = str, action = AggCommaString, default = "time time_bounds TFLAG ETFLAG latitude latitude_bounds longitude longitude_bounds lat lat_bnds lon lon_bnds etam_pressure etai_pressure layer_bounds layer47 layer".split(), metavar = "key1,key2", 
                        help = "Variables to be ignored in pncbo.")

    parser.add_argument("-v", "--variables", dest = "variables", default = None, action = AggCommaString,
                        metavar = 'varname1[,varname2[,...,varnameN]',
                        help = "Variable names or regular expressions (using match) separated by ','. If a group(s) has been specified, only variables in that (those) group(s) will be selected.")

    parser.add_argument("-a", "--attribute", dest = "attribute", type = str, action = "append", default = [], metavar = "att_nm,var_nm,mode,att_typ,att_val", 
                        help = "Variables have attributes that can be added following nco syntax (--attribute att_nm,var_nm,mode,att_typ,att_val); mode = a,c,d,m,o and att_typ = f,d,l,s,c,b; att_typ is any valid numpy type.")

    parser.add_argument("-m", "--mask", dest = "masks", action = "append", default = [],
                        help = "Masks to apply (e.g., greater,0 or less,0 or values,0, or where,(time[:]%%24<12)[:,None].repeat(10,1))")
        
    parser.add_argument("--from-convention", dest = "fromconv", type = str, default = None, help = "From convention currently only support ioapi")

    parser.add_argument("--to-convention", dest = "toconv", type = str, default = "cf", help = "To convention currently only supports cf")

    parser.add_argument("--stack", dest = "stack", type = str, help = "Concatentate (stack) files on the dimension.")
    
    parser.add_argument("--merge", dest = "merge", action = 'store_true', help = "Combine variables into one file")
    
    parser.add_argument("-s", "--slice", dest = "slice", type = str, action = "append", default = [], metavar = 'dim,start[,stop[,step]]',
                        help = "Variables have dimensions (time, layer, lat, lon), which can be subset using dim,start,stop,stride (e.g., --slice=layer,0,47,5 would sample every fifth layer starting at 0)")

    parser.add_argument("-r", "--reduce", dest = "reduce", type = str, action = "append", default = [], metavar = 'dim,function[,weight]', help = "Variable dimensions can be reduced using dim,function,weight syntax (e.g., --reduce=layer,mean,weight). Weighting is not fully functional.")

    parser.add_argument("--mesh", dest = "mesh", type = str, action = "append", default = [], metavar = 'dim,weight,function', help = "Variable dimensions can be meshed using dim,function,weight syntax (e.g., --mesh=time,0.5,mean).")
    
    parser.add_argument("-c", "--convolve", dest = "convolve", type = str, action = "append", default = [], metavar = 'dim,mode,wgt1,wgt2,...wgtN', help = "Variable dimension is reduced by convolve function (dim,mode,wgt1,wgt2,...wgtN)")    

    parser.add_argument("-e", "--extract", dest = "extract", action = "append", default = [],
                        help = "lon/lat coordinates to extract lon1,lat1/lon2,lat2/lon3,lat3/.../lonN,latN")

    parser.add_argument("--extractmethod", dest = "extractmethod", type = str, default = 'nn', choices = ['nn', 'linear', 'cubic', 'quintic', 'KDTree'],
                        help = "Method for extraction")

    
    parser.add_argument("--op-typ", dest = "operators", type = str, action = 'append', default = [], help = "Operator for binary file operations. Binary file operations use the first two files, then the result and the next file, etc. Use " + " or ".join(['//', '<=', '%%', 'is not', '>>', '&', '==', '!=', '+', '*', '-', '/', '<', '>=', '**', '>', '<<', '|', 'is', '^']))

    parser.add_argument("--expr", dest = "expressions", type = str, action = 'append', default = [], help = "Generic expressions to execute in the context of the file.")

    parser.add_argument("--exprscript", dest = "expressionscripts", type = str, action = 'append', default = [], help = "Generic expressions to execute in the context of the file.")
    if plot_options:
        parser.add_argument("--matplotlibrc", dest = "matplotlibrc", type = str, action = 'append', default = [], help = 'rc options for matplotlib')
        
        parser.add_argument("--plot-commands", dest = "plotcommands", type = str, action = 'append', default = [], help = "Plotting functions to call for all variables expressions to execute in the context of the file.")

        parser.add_argument("--figformat", dest = "figformat", type = str, default = 'png', help = "Any format supported by matplotlib")

        parser.add_argument("--norm", dest = "normalize", type = str, default = None, help = "Typical examples Normalize(), LogNorm(), BoundaryNorm([0, 10, 20, 30, 40], ncolors = 256)")

        parser.add_argument("--colorbar-formatter", dest = "colorbarformatter", type = str, default = None, help = "Typical examples LogFormatter(labelOnlyBase = False), ScalarFormatter(), '%%3g'")

        parser.add_argument("--coastlines", dest = "coastlines", type = bool, default = True, help = "Disable coastlines by setting equal to False")

        parser.add_argument("--countries", dest = "countries", type = bool, default = True, help = "Disable countries by setting equal to False")

        parser.add_argument("--states", dest = "states", type = bool, default = False, help = "Enable states by setting equal to True")

        parser.add_argument("--counties", dest = "counties", type = bool, default = False, help = "Enable counties by setting equal to True")

        parser.add_argument("--shapefiles", dest = "shapefiles", type = str, action = 'append', default = [], help = "Enable custom shapefiles (must be lon, lat)")

        parser.add_argument("--overlay", dest = "overlay", type = bool, default = False, help = "Enable overlay by setting equal to True")

    if interactive:
        parser.add_argument("-i", "--interactive", dest = "interactive", action = 'store_true', default = False, help = "Use interactive mode")
    return parser