我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用argparse.FileType()。
def text_to_speech_mp3_argparse(): description = 'Google TTS Downloader.' parser = argparse.ArgumentParser(description=description, epilog='tunnel snakes rule') parser.add_argument('-o', '--output', action='store', nargs='?', help='Filename to output audio to', type=argparse.FileType('wb'), default='out.mp3') parser.add_argument('-l', '--language', action='store', nargs='?', help='Language to output text to.', default='en') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-f', '--file', type=argparse.FileType('r'), help='File to read text from.') group.add_argument('-s', '--string', action='store', nargs='+', help='A string of text to convert to speech.') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args()
def _argparse(): argparse = ArgumentParser('bh_tsne Python wrapper') argparse.add_argument('-d', '--no_dims', type=int, default=DEFAULT_NO_DIMS) argparse.add_argument('-p', '--perplexity', type=float, default=DEFAULT_PERPLEXITY) # 0.0 for theta is equivalent to vanilla t-SNE argparse.add_argument('-t', '--theta', type=float, default=DEFAULT_THETA) argparse.add_argument('-r', '--randseed', type=int, default=EMPTY_SEED) argparse.add_argument('-n', '--initial_dims', type=int, default=INITIAL_DIMENSIONS) argparse.add_argument('-v', '--verbose', action='store_true') argparse.add_argument('-i', '--input', type=FileType('r'), default=stdin) argparse.add_argument('-o', '--output', type=FileType('w'), default=stdout) argparse.add_argument('--use_pca', action='store_true') argparse.add_argument('--no_pca', dest='use_pca', action='store_false') argparse.set_defaults(use_pca=DEFAULT_USE_PCA) argparse.add_argument('-m', '--max_iter', type=int, default=DEFAULT_MAX_ITERATIONS) return argparse
def main(): p = argparse.ArgumentParser() p.add_argument('--host', default='localhost', help='Hostname of voctocore') p.add_argument('--port', type=int, default=9999, help='Port to connect to, on voctocore') p.add_argument('--file', type=argparse.FileType('a'), help='Filename to write cuts to') args = p.parse_args() sock = socket.create_connection((args.host, args.port)) for cut in capture_cuts(sock): ts = datetime.datetime.now().strftime("%Y-%m-%d/%H_%M_%S") print(ts) sys.stdout.flush() if args.file: args.file.write('%s\n' % ts) args.file.flush()
def main(): parser = argparse.ArgumentParser() parser.add_argument( 'infile', type=argparse.FileType('r'), default=sys.stdin, ) parser.add_argument('-l', '--limit', type=float, default=0.005) parser.add_argument('-s', '--save') parser.add_argument('--show', action='store_true') args = parser.parse_args() data = parse_data(args.infile) for action in ['get', 'set', 'delete']: make_plot(data, action, args.save, args.show, args.limit)
def parse(self): # type: () -> App parser = StdErrArgumentParser(prog='puppeter', description='Puppeter - an automatic puppet installer', epilog='By default interactive setup is performed and chosen values can be saved' ' to answer file.') parser.add_argument('--answers', '-a', type=argparse.FileType('r'), metavar='FILE', help='An answer file to be used to perform unattended setup') parser.add_argument('--verbose', '-v', action='count', help='Print more verbose output (up to 2 verbosity flags are supported)') parser.add_argument('--version', action=_VersionAction, version='%(prog)s ' + puppeter.__version__) parser.add_argument('--execute', '-e', action='store_true', help='Executes setup commands instead of printing them') parsed = parser.parse_args(self.__argv) options = Options(parsed) apptype = 'interactive' if options.answers() is None else 'unattended' return container.get_named(App, apptype, options=options)
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
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( '--verbose', '-v', action="store_true", help="verbose mode.") parser.add_argument('--min-freq', '-f', type=int, default=2, help="minimum word frequency") return parser
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
def parse_args(): parser = argparse.ArgumentParser("coalesce_words") stdin = (sys.stdin.buffer if sys.version_info[0] >= 3 else sys.stdin) parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=stdin) parser.add_argument("--pages", nargs="+", type=parse_page_spec) parser.add_argument('--precision', default=1, choices=(0,1,2,3,4), type=int) parser.add_argument("--format", action="store", dest="format", choices=["csv", "json"], default="csv") args = parser.parse_args() return args
def run(cls, args=sys.argv[1:]): """Parse arguments and sign/verify.""" parser = argparse.ArgumentParser() parser.add_argument('--compact', action='store_true') subparsers = parser.add_subparsers() parser_sign = subparsers.add_parser('sign') parser_sign.set_defaults(func=cls.sign) parser_sign.add_argument( '-k', '--key', type=argparse.FileType('rb'), required=True) parser_sign.add_argument( '-a', '--alg', type=cls._alg_type, default=jwa.RS256) parser_sign.add_argument( '-p', '--protect', action='append', type=cls._header_type) parser_verify = subparsers.add_parser('verify') parser_verify.set_defaults(func=cls.verify) parser_verify.add_argument( '-k', '--key', type=argparse.FileType('rb'), required=False) parser_verify.add_argument( '--kty', type=cls._kty_type, required=False) parsed = parser.parse_args(args) return parsed.func(parsed)
def parse_cli(): parser = ArgumentParser(description='** Avtech Firmware signer By BigNerd95 **') subparser = parser.add_subparsers(dest='subparser_name') signParser = subparser.add_parser('sign', help='Sign firmware') signParser.add_argument('-i', '--input', required=True, metavar='INPUT_FILE', type=FileType('rb')) signParser.add_argument('-o', '--output', required=True, metavar='OUTPUT_FILE', type=FileType('wb')) signParser.add_argument('-p', '--product', required=True, metavar='PRODUCT_NAME') signParser.add_argument('-d', '--description', required=True, metavar='FILE_DESCRIPTION') signParser.add_argument('-v', '--version', required=True, metavar='FILE_VERSION') unsignParser = subparser.add_parser('unsign', help='Unsign firmware') unsignParser.add_argument('-i', '--input', required=True, metavar='INPUT_FILE', type=FileType('rb')) unsignParser.add_argument('-o', '--output', required=True, metavar='OUTPUT_FILE', type=FileType('wb')) infoParser = subparser.add_parser('info', help='Show firmware info') infoParser.add_argument('-i', '--input', required=True, metavar='INPUT_FILE', type=FileType('rb')) if len(sys.argv) < 2: parser.print_help() return parser.parse_args()
def main(argv): parser = argparse.ArgumentParser() parser.add_argument("input", type=argparse.FileType("r")) parser.add_argument("--using-qt", action="store_true") args = parser.parse_args(argv) if args.using_qt: from py2cpp import qt node = ast.parse(args.input.read()) conv = Converter() cpp_node = conv.visit(node) ctx = BuildContext.create() print("// generate by py2cpp") print("// original source code:", args.input.name) print('#include "py2cpp/py2cpp.hpp"\n') print(cpp_node.build(ctx)) return 0
def dive_export_sc(sc): sc = sc.add_parser('export', help='Writes props for DiVE visualization') sc.add_argument('fragmentsdb', type=str, help='Name of fragments db input file') uniprot_annot_help = '''Uniprot download accession 2 gene symbol, family mapping. Fetch "http://www.uniprot.org/uniprot/?query=database:pdb&format=tab&columns=id,genes(PREFERRED),families,database(PDB)" ''' sc.add_argument('uniprot_annot', type=argparse.FileType('r'), help=uniprot_annot_help) sc.add_argument('--propnames', type=argparse.FileType('w'), help='Name of prop names file', default='kripo.propnames.txt') sc.add_argument('--props', type=argparse.FileType('w'), help='Name of props file', default='kripo.props.txt') sc.add_argument('--pdbtags', type=argparse.FileType('r'), action='append', help='Tag pdb in file by filename') sc.set_defaults(func=dive_export)
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( '--verbose', '-v', action="store_true", help="verbose mode.") return parser
def add_pack_parser(parser): parser.description = """The pack command creates an NDEF record encapsulating the contents of FILE. The record type is determined by the file type if possible, it may be explicitely set with the -t option. The record name (payload identifier) is set to the file name.""" parser.set_defaults(func=pack) parser.add_argument( "-o", dest="outfile", metavar="FILE", type=argparse.FileType('w'), default="-", help="save to file (writes binary data)") parser.add_argument( "-t", metavar="STRING", dest="type", default="unknown", help="record type (default: mimetype)") parser.add_argument( "-n", metavar="STRING", dest="name", default=None, help="record name (default: pathname)") parser.add_argument( "input", metavar="FILE", type=argparse.FileType('r'), help="record data file ('-' to read from stdin)")
def add_split_parser(parser): parser.description = """The split command separates an an NDEF message into individual records. If data is read from a file, records are written as binary data into individual files with file names constructed from the input file base name, a hyphen followed by a three digit number and the input file name extension. If data is read from stdin, records are written to stdout as individual lines of hexadecimal strings.""" parser.set_defaults(func=split) parser.add_argument( "input", metavar="message", type=argparse.FileType('r'), help="message file ('-' to read from stdin)") parser.add_argument( "--keep-message-flags", dest="keepmf", action="store_true", help="do not reset message begin and end flags")
def add_emulate_parser(parser): parser.description = "Emulate an ndef tag." parser.add_argument( "-l", "--loop", action="store_true", help="continue (restart) after tag release") parser.add_argument( "-k", "--keep", action="store_true", help="keep tag memory (when --loop is set)") parser.add_argument( "-s", dest="size", type=int, default="1024", help="minimum ndef data area size (default: %(default)s)") parser.add_argument( "-p", dest="preserve", metavar="FILE", type=argparse.FileType('wb'), help="preserve tag memory when released") parser.add_argument( "input", metavar="FILE", type=argparse.FileType('r'), nargs="?", default=None, help="ndef message to serve ('-' reads from stdin)") subparsers = parser.add_subparsers(title="Tag Types", dest="tagtype") add_emulate_tt3_parser(subparsers.add_parser( 'tt3', help='emulate a type 3 tag'))
def __init__(self): """Sets up a command line parser, initialises logging and runs the specified module. """ # Set up command line parser. run_methods = [func[4:] for func in dir(__class__) if callable(getattr(__class__, func)) and func.startswith('run_')] parser = argparse.ArgumentParser(prog='sip_run.py', description='Run a SIP function.') parser.add_argument('module', help='Module to run.', choices=run_methods) parser.add_argument('-v', '--verbose', help='Enable verbose messages.', action='store_true') parser.add_argument('--config', '-c', type=argparse.FileType('r'), help='JSON configuration file.') self.args = parser.parse_args() # Initialise logging. self._log = self._init_logger() # Run the specified module. self._dispatch(self.args.module)
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))
def create_parser(): """Creat a commandline parser for epubcheck :return Argumentparser: """ parser = ArgumentParser( prog='epubcheck', description="EpubCheck v%s - Validate your ebooks" % __version__ ) # Arguments parser.add_argument( 'path', nargs='?', default=getcwd(), help="Path to EPUB-file or folder for batch validation. " "The current directory will be processed if this argument " "is not specified." ) # Options parser.add_argument( '-x', '--xls', nargs='?', type=FileType(mode='wb'), const='epubcheck_report.xls', help='Create a detailed Excel report.' ) parser.add_argument( '-c', '--csv', nargs='?', type=FileType(mode='wb'), const='epubcheck_report.csv', help='Create a CSV report.' ) parser.add_argument( '-r', '--recursive', action='store_true', help='Recurse into subfolders.' ) return parser
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))
def get_widget(action, widgets): """Summary Args: action (TYPE): Description widgets (TYPE): Description Returns: TYPE: Description """ 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
def main(args=None): parser = argparse.ArgumentParser(prog="cdma330disas", description="Corelink DMA-330 disassembler.") parser.add_argument("infile", help="Input file", type=argparse.FileType("rb")) parser.add_argument("-b", "--base-address", help="Base address", type=int, default=0) args = parser.parse_args() data = args.infile.read() args.infile.close() off = 0 lines = [] while off < len(data): newOff, instr = decodeInstruction(data, off) lines.append("{0:08X}: {1}".format(off+args.base_address, instr)) off = newOff print('\n'.join(lines))
def main(): parser = argparse.ArgumentParser(description='DNS resolver list checker') parser.add_argument('-o', '--output', metavar='OUTFILE', type=argparse.FileType('w+'), help="Output results to file") parser.add_argument('-r', '--resolvers', metavar='RESOLVERS_FILE', default=pkg_resources.resource_stream(__name__, "resolvers.txt"), type=argparse.FileType('r'), help="Load DNS resolver servers from file") parser.add_argument('-d', '--download', action='store_true', help='Download new list of resolvers from public-dns.info') parser.add_argument('-T', '--timeout', default=0.5, type=float, metavar='SECS', help="Timeout for DNS request in seconds, default: 0.5") parser.add_argument('-C', '--concurrency', default=10, type=int, help="Concurrent DNS requests, default: 10", metavar='N') parser.add_argument('-q', '--quiet', action='store_true', help="Don't print results to console") parser.add_argument('-v', '--verbose', action='store_const', dest="loglevel", const=logging.INFO, help="Log informational messages") parser.add_argument('--debug', action='store_const', dest="loglevel", const=logging.DEBUG, default=logging.WARNING, help="Log debugging messages") args = parser.parse_args() logging.basicConfig(level=args.loglevel) run(args)
def getArgs(): """ Parses command line arguments and returns them to the caller """ __version__ = 'v0.2.5' parser = argparse.ArgumentParser() parser._action_groups.pop() required = parser.add_argument_group('Required arguments') required.add_argument('-i', '--input', required=True, metavar='<FILE>', help='Input file in FASTA format') optional = parser.add_argument_group('Optional arguments') optional.add_argument('-o', '--output', type=argparse.FileType('w'), metavar='<FILE>', default=sys.stdout, help='Output file name. Default: Input file name + _perf.tsv') optional.add_argument('-a', '--analyse', action='store_true', default=False, help='Generate a summary HTML report.') cutoff_group = optional.add_mutually_exclusive_group() cutoff_group.add_argument('-l', '--min-length', type=int, metavar='<INT>', help='Minimum length cutoff of repeat') cutoff_group.add_argument('-u', '--min-units', metavar='INT or FILE', help="Minimum number of repeating units to be considered. Can be an integer or a file specifying cutoffs for different motif sizes.") optional.add_argument('-rep', '--repeats', type=argparse.FileType('r'), metavar='<FILE>', help='File with list of repeats (Not allowed with -m and/or -M)') optional.add_argument('-m', '--min-motif-size', type=int, metavar='<INT>', help='Minimum size of a repeat motif in bp (Not allowed with -rep)') optional.add_argument('-M', '--max-motif-size', type=int, metavar='<INT>', help='Maximum size of a repeat motif in bp (Not allowed with -rep)') optional.add_argument('-s', '--min-seq-length', type=int, metavar = '<INT>', default=0, help='Minimum size of sequence length for consideration (in bp)') optional.add_argument('-S', '--max-seq-length', type=float, metavar='<FLOAT>', default=inf, help='Maximum size of sequence length for consideration (in bp)') seqid_group = optional.add_mutually_exclusive_group() seqid_group.add_argument('-f', '--filter-seq-ids', metavar='<FILE>') seqid_group.add_argument('-F', '--target-seq-ids', metavar='<FILE>') optional.add_argument('--version', action='version', version='PERF ' + __version__) args = parser.parse_args() if args.repeats and (args.min_motif_size or args.max_motif_size): parser.error("-rep is not allowed with -m/-M") if args.repeats is None: if args.min_motif_size is None: args.min_motif_size = 1 if args.max_motif_size is None: args.max_motif_size = 6 if args.output.name == "<stdout>": args.output = open(splitext(args.input)[0] + '_perf.tsv', 'w') return args
def __init__(self, description): CmdLineTool.__init__(self, description) self.argParser.add_argument('-f', '--file', nargs='?', type = FileType('r'), default=sys.stdin, help='read input from the provided file') self.argParser.add_argument('-o', '--out', nargs='?', type= FileType('w'), default=sys.stdout, help = 'write output to provided file')
def main(): prog = 'python -m json.tool' description = ('A simple command line interface for json module ' 'to validate and pretty-print JSON objects.') parser = argparse.ArgumentParser(prog=prog, description=description) parser.add_argument('infile', nargs='?', type=argparse.FileType(), help='a JSON file to be validated or pretty-printed') parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), help='write the output of infile to outfile') parser.add_argument('--sort-keys', action='store_true', default=False, help='sort the output of dictionaries alphabetically by key') options = parser.parse_args() infile = options.infile or sys.stdin outfile = options.outfile or sys.stdout sort_keys = options.sort_keys with infile: try: if sort_keys: obj = json.load(infile) else: obj = json.load(infile, object_pairs_hook=collections.OrderedDict) except ValueError as e: raise SystemExit(e) with outfile: json.dump(obj, outfile, sort_keys=sort_keys, indent=4) outfile.write('\n')
def main(): """Command line entry point.""" import argparse import sys parser = argparse.ArgumentParser( description=sys.modules[__name__].__doc__) parser.add_argument( 'article_file', metavar='ARTICLE', type=argparse.FileType(), help='path to Wiktionary article file') parser.add_argument( '-z', '--zim-file', action='store_true', help='treat the article file as a ZIM archive, instead of HTML ' 'source') parser.add_argument( '-d', '--debug', action='store_true', help='enable debugging output') args = parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO) if args.zim_file: article_tuples = ZimFile(args.article_file).article_tuples() else: article_tuples = [(None, None, args.article_file.read())] for article_tuple in article_tuples: context = {'edition': article_tuple[0], 'pagename': article_tuple[1]} doc = html.fromstring(article_tuple[2]) for translation in parse_document(doc): translation.update(context) print json.dumps(translation)
def main(): # Check arguments parser = argparse.ArgumentParser() parser.add_argument('pot_filename', type=argparse.FileType('r')) parser.add_argument('po_filename', type=argparse.FileType('w')) parser.add_argument('locale') args = parser.parse_args() # read POT file pot_cat = pofile.read_po(args.pot_filename, ignore_obsolete=True) # Create the new Catalog new_cat = catalog.Catalog(locale=args.locale, last_translator="pseudo.py", charset="utf-8") num_plurals = new_cat.num_plurals # Process messages from template for msg in pot_cat: if msg.pluralizable: msg.string = [translate(u"{}:{}".format(i, msg.id[0])) for i in range(num_plurals)] else: msg.string = translate(msg.id) new_cat[msg.id] = msg # Write "translated" PO file pofile.write_po(args.po_filename, new_cat, ignore_obsolete=True)