Python argparse.FileType() Examples
The following are 30
code examples of argparse.FileType().
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 also want to check out all available functions/classes of the module
argparse
, or try the search function
.
Example #1
Source File: apply_bpe.py From crosentgec with GNU General Public License v3.0 | 8 votes |
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 #2
Source File: images_to_json.py From cloudml-samples with Apache License 2.0 | 7 votes |
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 #3
Source File: full_message_encrypt.py From aws-encryption-sdk-python with Apache License 2.0 | 6 votes |
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 #4
Source File: __init__.py From recipes-py with Apache License 2.0 | 6 votes |
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 #5
Source File: batch.py From aegea with Apache License 2.0 | 6 votes |
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 #6
Source File: __init__.py From python-panavatar with MIT License | 6 votes |
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 #7
Source File: notes_import.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #8
Source File: cliparser.py From indic_nlp_library with MIT License | 6 votes |
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 #9
Source File: cliparser.py From indic_nlp_library with MIT License | 6 votes |
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 #10
Source File: cliparser.py From indic_nlp_library with MIT License | 6 votes |
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 #11
Source File: receiver.py From agogosml with MIT License | 6 votes |
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 #12
Source File: sender.py From agogosml with MIT License | 6 votes |
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 #13
Source File: learn_bpe.py From knmt with GNU General Public License v3.0 | 6 votes |
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 #14
Source File: gen_corpus.py From Living-Audio-Dataset with Apache License 2.0 | 6 votes |
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 #15
Source File: key_tool.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #16
Source File: __init__.py From lkml with MIT License | 6 votes |
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 #17
Source File: prep-genome.py From kevlar with MIT License | 6 votes |
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 #18
Source File: __main__.py From GraphvizAnim with GNU General Public License v3.0 | 5 votes |
def main(): parser = ArgumentParser( prog = 'gvanim' ) parser.add_argument( 'animation', nargs = '?', type = FileType( 'r' ), default = stdin, help = 'The file containing animation commands (default: stdin)' ) parser.add_argument( '--delay', '-d', default = '100', help = 'The delay (in ticks per second, default: 100)' ) parser.add_argument( 'basename', help = 'The basename of the generated file' ) args = parser.parse_args() ga = Animation() ga.parse( args.animation ) gif( render( ga.graphs(), args.basename, 'png' ), args.basename, args.delay )
Example #19
Source File: cli.py From tmhmm.py with MIT License | 5 votes |
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 #20
Source File: recording_script_gen.py From Living-Audio-Dataset with Apache License 2.0 | 5 votes |
def main(): parser = argparse.ArgumentParser() parser.add_argument("-g", "--genre", default = 'z', help = "genre") parser.add_argument("-n", "--no-utterances", default = 999, type=int, help = "how many utterances") parser.add_argument("-s", "--search-width", default = 100, type=int, help = "how many utterances to consider when finding the next one for the script (-1 means all)") parser.add_argument("-m", "--max-words", default = 15, type=int, help = "discard utterances with more than this amount of words") parser.add_argument("-i", "--input", action = "append", required = True, type = argparse.FileType('r'), help = "input file (can be given multiple times)") parser.add_argument("-o", "--output", default = 'text.xml', type = argparse.FileType('w'), help = "output recording script") args = parser.parse_args() if len(args.genre) > 1 or not re.match(r'[a-z]', args.genre): parser.error('genre must be a single letter') stats = [] for fin in args.input: fstats = json.load(fin) for st in fstats['stats']: for s in st: if s['prompt'] and s['no_tokens'] <= args.max_words: stats.append(s) script = stats2script(stats, args.search_width, args.no_utterances) scriptxml = scrit2xml(script, args.genre) args.output.write(lxml.etree.tostring(scriptxml, pretty_print=True, xml_declaration=True, encoding='utf-8').decode('utf-8')) args.output.write('\n')
Example #21
Source File: apply_bpe.py From knmt with GNU General Public License v3.0 | 5 votes |
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 #22
Source File: chardetect.py From jawfish with MIT License | 5 votes |
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
Source File: export.py From grimoirelab-sortinghat with GNU General Public License v3.0 | 5 votes |
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 #24
Source File: main.py From query-exporter with GNU General Public License v3.0 | 5 votes |
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 #25
Source File: test_argparse.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_r(self): type = argparse.FileType('r') self.assertEqual("FileType('r')", repr(type))
Example #26
Source File: test_argparse.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_wb_1(self): type = argparse.FileType('wb', 1) self.assertEqual("FileType('wb', 1)", repr(type))
Example #27
Source File: chardetect.py From lambda-chef-node-cleanup with Apache License 2.0 | 5 votes |
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 #28
Source File: __main__.py From anishot with MIT License | 5 votes |
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 #29
Source File: chardetect.py From NEIE-Assistant with GNU General Public License v3.0 | 5 votes |
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 #30
Source File: chardetect.py From SalesforceXyTools with Apache License 2.0 | 5 votes |
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))