Python argparse.FileType() Examples

The following are 30 code examples for showing how to use argparse.FileType(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: aegea   Author: kislyuk   File: batch.py    License: Apache License 2.0 6 votes vote down vote up
def add_command_args(parser):
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--watch", action="store_true", help="Monitor submitted job, stream log until job completes")
    group.add_argument("--wait", action="store_true",
                       help="Block on job. Exit with code 0 if job succeeded, 1 if failed")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--command", nargs="+", help="Run these commands as the job (using " + BOLD("bash -c") + ")")
    group.add_argument("--execute", type=argparse.FileType("rb"), metavar="EXECUTABLE",
                       help="Read this executable file and run it as the job")
    group.add_argument("--wdl", type=argparse.FileType("rb"), metavar="WDL_WORKFLOW",
                       help="Read this WDL workflow file and run it as the job")
    parser.add_argument("--wdl-input", type=argparse.FileType("r"), metavar="WDL_INPUT_JSON", default=sys.stdin,
                        help="With --wdl, use this JSON file as the WDL job input (default: stdin)")
    parser.add_argument("--environment", nargs="+", metavar="NAME=VALUE",
                        type=lambda x: dict(zip(["name", "value"], x.split("=", 1))), default=[])
    parser.add_argument("--staging-s3-bucket", help=argparse.SUPPRESS) 
Example 2
Project: python-panavatar   Author: ondergetekende   File: __init__.py    License: MIT License 6 votes vote down vote up
def cmdline():
    import argparse

    parser = argparse.ArgumentParser(description='Generate an svg wallpaper')
    parser.add_argument('--width', type=int, default=1024,
                        help='The width of the wallpaper')
    parser.add_argument('--height', type=int, default=786,
                        help='The height of the wallpaper')
    parser.add_argument('--seed',
                        help='Seed for the randomizer')
    parser.add_argument('--log-choices',
                        help='Log the choices made', action='store_true')

    parser.add_argument('--output', type=argparse.FileType('w'),
                        default='-')

    args = parser.parse_args()

    for element in get_svg_iter(args.width, args.height,
                                {"seed": args.seed},
                                log_choices=args.log_choices):
        args.output.write(element) 
Example 3
Project: recipes-py   Author: luci   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def add_arguments(parser):
  parser.add_argument(
      '--output-json',
      type=argparse.FileType('w'),
      help='A json file to output information about the roll to.')
  parser.add_argument(
      '--verbose-json',
      action='store_true',
      help=(
        'Emit even more data in the output-json file. Requires --output-json.'
      ))

  def _launch(args):
    from .cmd import main
    return main(args)
  def _postprocess_func(error, args):
    if args.verbose_json and not args.output_json:
      error('--verbose-json passed without --output-json')

  parser.set_defaults(
      func=_launch, postprocess_func=_postprocess_func) 
Example 4
Project: coursys   Author: sfu-fas   File: notes_import.py    License: GNU General Public License v3.0 6 votes vote down vote up
def add_arguments(self, parser):

        parser.add_argument('input_file', type=argparse.FileType('r'), help='The file to process')
        parser.add_argument('unit', type=str,
                            help='The short name of the unit all the notes will be added under, (e.g. "CMPT")')
        parser.add_argument('--dry-run', '-n',
                            action='store_true',
                            dest='dry_run',
                            help='Don\'t actually save the data',
                            default=False,
                            )
        parser.add_argument('--verbose',
                            action='store_true',
                            dest='verbose',
                            help='Print verbose output.  Same as setting -v > 1',
                            default=False)
        parser.add_argument('--markup', '-m',
                            dest='markup',
                            default='html',
                            help='Choices are: %s.' % get_markup_choices()) 
Example 5
Project: indic_nlp_library   Author: anoopkunchukuttan   File: cliparser.py    License: MIT License 6 votes vote down vote up
def add_common_monolingual_args(task_parser):
    task_parser.add_argument('infile', 
                type=argparse.FileType('r',encoding=DEFAULT_ENCODING),
                nargs='?',
                default=sys.stdin,
                help='Input File path',
            )
    task_parser.add_argument('outfile', 
                type=argparse.FileType('w',encoding=DEFAULT_ENCODING),
                nargs='?',
                default=sys.stdout,                
                help='Output File path',
            )
    task_parser.add_argument('-l', '--lang', 
                help='Language',
            ) 
Example 6
Project: indic_nlp_library   Author: anoopkunchukuttan   File: cliparser.py    License: MIT License 6 votes vote down vote up
def add_common_bilingual_args(task_parser):
    task_parser.add_argument('infile', 
                type=argparse.FileType('r',encoding=DEFAULT_ENCODING),
                nargs='?',
                default=sys.stdin,
                help='Input File path',
            )
    task_parser.add_argument('outfile', 
                type=argparse.FileType('w',encoding=DEFAULT_ENCODING),
                nargs='?',
                default=sys.stdout,                
                help='Output File path',
            )
    task_parser.add_argument('-s', '--srclang', 
                help='Source Language',
            )

    task_parser.add_argument('-t', '--tgtlang', 
                help='Target Language',
            ) 
Example 7
Project: indic_nlp_library   Author: anoopkunchukuttan   File: cliparser.py    License: MIT License 6 votes vote down vote up
def add_wc_parser(subparsers):
    task_parser=subparsers.add_parser('wc', help='wc help')

    task_parser.add_argument('infile', 
                type=argparse.FileType('r',encoding=DEFAULT_ENCODING),
                nargs='?',
                default=sys.stdin,
                help='Input File path',
            )
    # task_parser.add_argument('-l', action='store_true')
    # task_parser.add_argument('-w', action='store_true')
    # task_parser.add_argument('-c', action='store_true')
    # task_parser.set_defaults(l=False)
    # task_parser.set_defaults(w=False)
    # task_parser.set_defaults(c=False)

    task_parser.set_defaults(func=run_wc) 
Example 8
Project: crosentgec   Author: nusnlp   File: apply_bpe.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_parser():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="learn BPE-based word segmentation")

    parser.add_argument(
        '--input', '-i', type=argparse.FileType('r'), default=sys.stdin,
        metavar='PATH',
        help="Input file (default: standard input).")
    parser.add_argument(
        '--codes', '-c', type=argparse.FileType('r'), metavar='PATH',
        required=True,
        help="File with BPE codes (created by learn_bpe.py).")
    parser.add_argument(
        '--output', '-o', type=argparse.FileType('w'), default=sys.stdout,
        metavar='PATH',
        help="Output file (default: standard output)")
    parser.add_argument(
        '--separator', '-s', type=str, default='@@', metavar='STR',
        help="Separator between non-final subword units (default: '%(default)s'))")

    return parser 
Example 9
Project: agogosml   Author: microsoft   File: receiver.py    License: MIT License 6 votes vote down vote up
def cli():
    """Command-line interface to the tool."""
    streaming_clients = find_streaming_clients()

    parser = ArgumentParser(description=__doc__)
    parser.add_argument('--outfile', type=FileType('wb', encoding='utf-8'),
                        default=stdout,
                        help='File to which to write events')
    parser.add_argument('--receiver', choices=sorted(streaming_clients),
                        required=True, default='kafka',
                        help='The receiver to use')
    parser.add_argument('config', type=json_arg,
                        help='JSON configuration passed to the receiver')
    args = parser.parse_args()

    receive(args.outfile, streaming_clients[args.receiver], args.config) 
Example 10
Project: agogosml   Author: microsoft   File: sender.py    License: MIT License 6 votes vote down vote up
def cli():
    """Command-line interface to the tool."""
    streaming_clients = find_streaming_clients()

    parser = ArgumentParser(description=__doc__)
    parser.add_argument('--infile', type=FileType('r', encoding='utf-8'),
                        default=stdin,
                        help='File with events to send')
    parser.add_argument('--sender', choices=sorted(streaming_clients),
                        required=True, default='kafka',
                        help='The sender to use')
    parser.add_argument('config', type=json_arg,
                        help='JSON configuration passed to the sender')
    args = parser.parse_args()

    send(args.infile, streaming_clients[args.sender], args.config) 
Example 11
Project: knmt   Author: fabiencro   File: learn_bpe.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_parser():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="learn BPE-based word segmentation")

    parser.add_argument(
        '--input', '-i', type=argparse.FileType('r'), default=sys.stdin,
        metavar='PATH',
        help="Input text (default: standard input).")
    parser.add_argument(
        '--output', '-o', type=argparse.FileType('w'), default=sys.stdout,
        metavar='PATH',
        help="Output file for BPE codes (default: standard output)")
    parser.add_argument(
        '--symbols', '-s', type=int, default=10000,
        help="Create this many new symbols (each representing a character n-gram) (default: %(default)s))")
    parser.add_argument(
        '--min-frequency', type=int, default=2, metavar='FREQ',
        help='Stop if no symbol pair has frequency >= FREQ (default: %(default)s))')
    parser.add_argument(
        '--verbose', '-v', action="store_true",
        help="verbose mode.")

    return parser 
Example 12
Project: cloudml-samples   Author: GoogleCloudPlatform   File: images_to_json.py    License: Apache License 2.0 6 votes vote down vote up
def parse_args():
  """Handle the command line arguments.

  Returns:
    Output of argparse.ArgumentParser.parse_args.
  """

  parser = argparse.ArgumentParser()
  parser.add_argument('-o', '--output', default='request.json',
                      help='Output file to write encoded images to.')
  parser.add_argument('-r', '--resize', dest='resize', action='store_true',
                      help='Will resize images locally first.  Not needed, but'
                      ' will reduce network traffic.')
  parser.add_argument('inputs', nargs='+', type=argparse.FileType('r'),
                      help='A list of .jpg or .jpeg files to serialize into a '
                      'request json')

  args = parser.parse_args()

  check = lambda filename: filename.lower().endswith(('jpeg', 'jpg'))
  if not all(check(input_file.name) for input_file in args.inputs):
    sys.stderr.write('All inputs must be .jpeg or .jpg')
    sys.exit(1)

  return args 
Example 13
Project: Living-Audio-Dataset   Author: Idlak   File: gen_corpus.py    License: Apache License 2.0 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", "--max-no-articles", type = int, default=10,
                        help = "maximum number of articles to download")
    parser.add_argument("-w", "--no-words", type = int, default=1000000,
                        help = "target number of words")

    parser.add_argument("-s", "--search",
                        help = "if specified will use this search term")

    parser.add_argument("language",
                        help = "2 letter language code")

    parser.add_argument("output", type = argparse.FileType('w'),
                        help = "output file")

    args = parser.parse_args()
    articles = get_articles(**vars(args))
    corpusxml = articles2xml(articles)

    xmlstr = lxml.etree.tostring(corpusxml,
                                 pretty_print=True,
                                 xml_declaration=True,
                                 encoding='utf-8')
    args.output.write(xmlstr.decode('utf-8')) 
Example 14
Project: king-phisher   Author: rsmusllp   File: key_tool.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
	parser = argparse.ArgumentParser(description='King Phisher Signing-Key Generation Utility', conflict_handler='resolve')
	utilities.argp_add_args(parser)
	subparsers = parser.add_subparsers(dest='subcommand')
	subparsers.required = True

	parser_display = subparsers.add_parser('display')
	parser_display.set_defaults(action=action_display)
	parser_display.add_argument('file', default=os.getenv('KING_PHISHER_DEV_KEY'), nargs='?', help='the key file to display')

	parser_generate = subparsers.add_parser('generate')
	parser_generate.set_defaults(action=action_generate)
	parser_generate.add_argument('id', help='this key\'s identifier')
	parser_generate.add_argument('file', type=argparse.FileType('w'), help='the destination to write the key to')
	arguments = parser.parse_args()

	find.init_data_path()
	arguments.action(arguments) 
Example 15
Project: lkml   Author: joshtemple   File: __init__.py    License: MIT License 6 votes vote down vote up
def parse_args(args: Sequence) -> argparse.Namespace:
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        description=(
            "A blazing fast LookML parser, implemented in pure Python. "
            "When invoked from the command line, "
            "returns the parsed output as a JSON string."
        )
    )
    parser.add_argument(
        "file", type=argparse.FileType("r"), help="path to the LookML file to parse"
    )
    parser.add_argument(
        "-d",
        "--debug",
        action="store_const",
        dest="log_level",
        const=logging.DEBUG,
        default=logging.WARN,
        help="increase logging verbosity",
    )

    return parser.parse_args(args) 
Example 16
Project: kevlar   Author: kevlar-dev   File: prep-genome.py    License: MIT License 6 votes vote down vote up
def get_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('--discard', metavar='RE', type=str, nargs='+',
                        default=None, help='regex(es) of sequence ID(s) to '
                        'discard')
    parser.add_argument('--debug', action='store_true',
                        help='print debugging output')
    parser.add_argument('--minlength', type=int, default=10000,
                        help='minimum length of sequences to keep after '
                        'removing ambiguous nucleotides; default is 10000')
    parser.add_argument('--outfile', metavar='FILE', default=sys.stdout,
                        type=argparse.FileType('w'), help='output fasta file '
                        '(prints to terminal by default)')
    parser.add_argument('infile', metavar='FILE', type=argparse.FileType('r'),
                        help='input fasta file (- for standard input)')
    return parser 
Example 17
Project: aws-encryption-sdk-python   Author: aws   File: full_message_encrypt.py    License: Apache License 2.0 6 votes vote down vote up
def cli(args=None):
    # type: (Optional[Iterable[str]]) -> None
    """CLI entry point for processing AWS Encryption SDK Encrypt Message manifests."""
    parser = argparse.ArgumentParser(
        description="Build ciphertexts and decrypt manifest from keys and encrypt manifests"
    )
    parser.add_argument("--output", required=True, help="Directory in which to store results")
    parser.add_argument(
        "--input", required=True, type=argparse.FileType("r"), help="Existing full message encrypt manifest"
    )
    parser.add_argument(
        "--human",
        required=False,
        default=None,
        action="store_const",
        const=4,
        dest="json_indent",
        help="Output human-readable JSON",
    )

    parsed = parser.parse_args(args)

    encrypt_manifest = MessageEncryptionManifest.from_file(parsed.input)

    encrypt_manifest.run_and_write_to_dir(target_directory=parsed.output, json_indent=parsed.json_indent) 
Example 18
Project: anishot   Author: sourcerer-io   File: __main__.py    License: MIT License 5 votes vote down vote up
def parse_arguments():
    parser = argparse.ArgumentParser(
        description='Animates a long screenshot into a GIF')
    parser.add_argument('input', type=argparse.FileType(),
                        help='Input screenshot image')
    parser.add_argument('output', type=str,
                        help='Output animated GIF')
    parser.add_argument('height', type=int,
                        help='Window height')
    parser.add_argument('--pad', default=0, type=int,
                        help='Padding on sides')
    parser.add_argument('--maxspeed', default=200, type=int,
                        help='Max speed on scroll px/frame')
    parser.add_argument('--stops', nargs='*', default=[],
                        help='Stops between scrolls, px')
    parser.add_argument('--zoom-steps', default=7, type=int,
                        help='Number of steps on initial zoom in')
    parser.add_argument('--start-scale', default=.7, type=float,
                        help='Start scale')
    parser.add_argument('--zoom-to', default=0, type=int,
                        help='Point to zoom to')
    parser.add_argument('--shadow-size', default=0, type=int,
                        help='Shadow size')
    parser.add_argument('--rgb-outline', default='#e1e4e8', type=str,
                        help='Screenshot outline color')
    parser.add_argument('--rgb-background', default='#ffffff', type=str,
                        help='Background color')
    parser.add_argument('--rgb-shadow', default='#999999', type=str,
                        help='Screenshot shadow color')
    parser.add_argument('--rgb-window', default='#e1e4e8', type=str,
                        help='Window outline color')
    global ARGS
    ARGS = parser.parse_args() 
Example 19
Project: query-exporter   Author: albertodonato   File: main.py    License: GNU General Public License v3.0 5 votes vote down vote up
def configure_argument_parser(self, parser: argparse.ArgumentParser):
        parser.add_argument(
            "config", type=argparse.FileType("r"), help="configuration file"
        )
        parser.add_argument(
            "-V", "--version", action="version", version=f"%(prog)s {__version__}",
        )
        parser.add_argument(
            "--check-only",
            action="store_true",
            help="only check configuration, don't run the exporter",
        )
        autocomplete(parser) 
Example 20
Project: tmhmm.py   Author: dansondergaard   File: cli.py    License: MIT License 5 votes vote down vote up
def cli():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--file', dest='sequence_file',
                        type=argparse.FileType('r'), required=True,
                        help='path to file in fasta format with sequences')
    parser.add_argument('-m', '--model', dest='model_file',
                        type=argparse.FileType('r'), default=DEFAULT_MODEL,
                        help='path to the model to use')
    if has_matplotlib:
        parser.add_argument('-p', '--plot', dest='plot_posterior',
                            action='store_true',
                            help='plot posterior probabilies')

    args = parser.parse_args()

    header, model = parse(args.model_file)
    for entry in load_fasta_file(args.sequence_file):
        path, posterior = predict(entry.sequence, header, model)

        with open(entry.id + '.summary', 'w') as summary_file:
            for start, end, state in summarize(path):
                print("{} {} {}".format(start, end, PRETTY_NAMES[state]),
                      file=summary_file)

        with open(entry.id + '.annotation', 'w') as ann_file:
            print('>', entry.id, ' ', entry.description, sep='', file=ann_file)
            for line in textwrap.wrap(path, 79):
                print(line, file=ann_file)

        plot_filename = entry.id + '.plot'
        with open(plot_filename, 'w') as plot_file:
            dump_posterior_file(plot_file, posterior)

        if hasattr(args, 'plot_posterior') and args.plot_posterior:
            with open(plot_filename, 'r') as fileobj:
                plot(fileobj, entry.id + '.pdf') 
Example 21
Project: grimoirelab-sortinghat   Author: chaoss   File: export.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super(Export, self).__init__(**kwargs)

        self.parser = argparse.ArgumentParser(description=self.description,
                                              usage=self.usage)

        # Actions
        group = self.parser.add_mutually_exclusive_group(required=True)
        group.add_argument('--identities', action='store_true',
                           help="export identities")
        group.add_argument('--orgs', action='store_true',
                           help="export organizations")

        # General options
        self.parser.add_argument('--source', dest='source', default=None,
                                 help="source of the identities to export")

        # Positional arguments
        self.parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
                                 default=sys.stdout,
                                 help="output file")

        # Exit early if help is requested
        if 'cmd_args' in kwargs and [i for i in kwargs['cmd_args'] if i in HELP_LIST]:
            return

        self._set_database(**kwargs) 
Example 22
Project: jawfish   Author: war-and-code   File: chardetect.py    License: MIT License 5 votes vote down vote up
def main(argv=None):
    '''
    Handles command line arguments and gets things started.

    :param argv: List of arguments, as if specified on the command-line.
                 If None, ``sys.argv[1:]`` is used instead.
    :type argv: list of str
    '''
    # Get command line arguments
    parser = argparse.ArgumentParser(
        description="Takes one or more file paths and reports their detected \
                     encodings",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        conflict_handler='resolve')
    parser.add_argument('input',
                        help='File whose encoding we would like to determine.',
                        type=argparse.FileType('rb'), nargs='*',
                        default=[sys.stdin])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(__version__))
    args = parser.parse_args(argv)

    for f in args.input:
        if f.isatty():
            print("You are running chardetect interactively. Press " +
                  "CTRL-D twice at the start of a blank line to signal the " +
                  "end of your input. If you want help, run chardetect " +
                  "--help\n", file=sys.stderr)
        print(description_of(f, f.name)) 
Example 23
Project: gist-alfred   Author: danielecook   File: chardetect.py    License: MIT License 5 votes vote down vote up
def main(argv=None):
    """
    Handles command line arguments and gets things started.

    :param argv: List of arguments, as if specified on the command-line.
                 If None, ``sys.argv[1:]`` is used instead.
    :type argv: list of str
    """
    # Get command line arguments
    parser = argparse.ArgumentParser(
        description="Takes one or more file paths and reports their detected \
                     encodings")
    parser.add_argument('input',
                        help='File whose encoding we would like to determine. \
                              (default: stdin)',
                        type=argparse.FileType('rb'), nargs='*',
                        default=[sys.stdin if PY2 else sys.stdin.buffer])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(__version__))
    args = parser.parse_args(argv)

    for f in args.input:
        if f.isatty():
            print("You are running chardetect interactively. Press " +
                  "CTRL-D twice at the start of a blank line to signal the " +
                  "end of your input. If you want help, run chardetect " +
                  "--help\n", file=sys.stderr)
        print(description_of(f, f.name)) 
Example 24
Project: me-ica   Author: ME-ICA   File: argparse_to_json.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_widget(action, widgets):
  supplied_widget = widgets.get(action.dest, None)
  type_arg_widget = 'FileChooser' if action.type == argparse.FileType else None
  return supplied_widget or type_arg_widget or None 
Example 25
Project: VxAPI   Author: PayloadSecurity   File: default_cli_arguments.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add_file_with_hash_list_arg(self, allowed_hashes):
        self.parser.add_argument('hashes-file', type=argparse.FileType('r'), help='Path to file containing list of sample hashes separated by new line (allowed: {})'.format(', '.join(allowed_hashes)))

        return self 
Example 26
Project: VxAPI   Author: PayloadSecurity   File: default_cli_arguments.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add_file_with_ids_arg(self, allowed_ids):
        self.parser.add_argument('mixed-ids-file', type=argparse.FileType('r'), help='Path to file containing list of ids (allowed: {}'.format(', '.join(allowed_ids)))

        return self 
Example 27
Project: misp42splunk   Author: remg427   File: chardetect.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(argv=None):
    """
    Handles command line arguments and gets things started.

    :param argv: List of arguments, as if specified on the command-line.
                 If None, ``sys.argv[1:]`` is used instead.
    :type argv: list of str
    """
    # Get command line arguments
    parser = argparse.ArgumentParser(
        description="Takes one or more file paths and reports their detected \
                     encodings")
    parser.add_argument('input',
                        help='File whose encoding we would like to determine. \
                              (default: stdin)',
                        type=argparse.FileType('rb'), nargs='*',
                        default=[sys.stdin if PY2 else sys.stdin.buffer])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(__version__))
    args = parser.parse_args(argv)

    for f in args.input:
        if f.isatty():
            print("You are running chardetect interactively. Press " +
                  "CTRL-D twice at the start of a blank line to signal the " +
                  "end of your input. If you want help, run chardetect " +
                  "--help\n", file=sys.stderr)
        print(description_of(f, f.name)) 
Example 28
Project: misp42splunk   Author: remg427   File: chardetect.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(argv=None):
    """
    Handles command line arguments and gets things started.

    :param argv: List of arguments, as if specified on the command-line.
                 If None, ``sys.argv[1:]`` is used instead.
    :type argv: list of str
    """
    # Get command line arguments
    parser = argparse.ArgumentParser(
        description="Takes one or more file paths and reports their detected \
                     encodings")
    parser.add_argument('input',
                        help='File whose encoding we would like to determine. \
                              (default: stdin)',
                        type=argparse.FileType('rb'), nargs='*',
                        default=[sys.stdin if PY2 else sys.stdin.buffer])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(__version__))
    args = parser.parse_args(argv)

    for f in args.input:
        if f.isatty():
            print("You are running chardetect interactively. Press " +
                  "CTRL-D twice at the start of a blank line to signal the " +
                  "end of your input. If you want help, run chardetect " +
                  "--help\n", file=sys.stderr)
        print(description_of(f, f.name)) 
Example 29
Project: recipes-py   Author: luci   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def add_arguments(parser):
  parser.add_argument(
    'input', type=argparse.FileType('r'),
    help='Path to a JSON object. Valid fields: "files", "recipes". See'
         ' analyze.proto file for more information')
  parser.add_argument(
    'output', type=argparse.FileType('w'), default=sys.stdout,
    help='The file to write output to. See analyze.proto for more information.')

  def _launch(args):
    from .cmd import main
    return main(args)
  parser.set_defaults(func=_launch) 
Example 30
Project: mergevcf   Author: ljdursi   File: __init__.py    License: MIT License 5 votes vote down vote up
def main():
    """Merge VCF files, output to stdout or file"""
    defsvwindow = 100

    parser = argparse.ArgumentParser(description='Merge calls in VCF files')
    parser.add_argument('input_files', nargs='+', help='Input VCF files')
    parser.add_argument('-o', '--output', type=argparse.FileType('w'), default=sys.stdout, help="Specify output file (default:stdout)") 
    parser.add_argument('-v', '--verbose', action='store_true', help="Specify verbose output")
    parser.add_argument('-l', '--labels', type=str, help='Comma-separated labels for each input VCF file (default:basenames)')
    parser.add_argument('-n', '--ncallers', action='store_true', help='Annotate variant with number of callers')
    parser.add_argument('-m', '--mincallers', type=int, default=0, help='Minimum # of callers for variant to pass')
    parser.add_argument('-s', '--sv', action='store_true', help='Force interpretation as SV (default:false)')
    parser.add_argument('-f', '--filtered', action='store_true', help='Include records that have failed one or more filters (default:false)')
    parser.add_argument('-w', '--svwindow', default=defsvwindow, type=int,
                         help='Window for comparing breakpoint positions for SVs (default:'+str(defsvwindow)+')')

    args = parser.parse_args()
    input_files = args.input_files
    if args.labels is None:
        labels = [os.path.splitext(os.path.basename(f))[0] for f in input_files]
    else:
        labels = [label.strip() for label in args.labels.split(',')]

    mergedfile.merge(input_files, labels, args.sv, args.output,
                     slop=args.svwindow, verbose=args.verbose,
                     output_ncallers=args.ncallers,
                     min_num_callers=args.mincallers,
                     filterByChromosome=True, noFilter=args.filtered)