Python argparse.FileType() Examples

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

Example 1
Project: GDot   Author: pointhi   File: gdot.py    GNU General Public License v3.0 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='GUI to edit and view graphviz files')
    parser.add_argument('dotfile', nargs='?', type=argparse.FileType('r'))

    args = parser.parse_args()

    # load our main application
    gdot = GDot()

    # load file if specified
    if args.dotfile:
        gdot.load_file(args.dotfile)

    # workaround to support KeyboardInterrupt
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    # startup gui
    Gtk.main() 
Example 2
Project: pcfg-sampling   Author: wilkeraziz   File: binarizable.py    Apache License 2.0 6 votes vote down vote up
def argparser():
    """parse command line arguments"""

    parser = argparse.ArgumentParser(prog='parse')

    parser.description = 'Binarizable permutations'
    parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter

    parser.add_argument('input', nargs='?', 
            type=argparse.FileType('r'), default=sys.stdin,
            help='input corpus (one sentence per line)')
    #parser.add_argument('output', nargs='?', 
    #        type=argparse.FileType('w'), default=sys.stdout,
    #        help='parse trees')
    parser.add_argument('--show-permutations', 
            action='store_true',
            help='enumerate permutations (use with care)')
    parser.add_argument('--verbose', '-v',
            action='store_true',
            help='increase the verbosity level')

    return parser 
Example 3
Project: pcfg-sampling   Author: wilkeraziz   File: itg-parse.py    Apache License 2.0 6 votes vote down vote up
def argparser():
    """parse command line arguments"""

    parser = argparse.ArgumentParser(prog='parse')

    parser.description = 'Earley parser'
    parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter

    parser.add_argument('grammar',  
            type=argparse.FileType('r'), 
            help='CFG rules')
    parser.add_argument('input', nargs='?', 
            type=argparse.FileType('r'), default=sys.stdin,
            help='input corpus (one sentence per line)')
    parser.add_argument('--show-permutations',
            action='store_true',
            help='dumps all permutations (use with caution)')
    parser.add_argument('--verbose', '-v',
            action='store_true',
            help='increase the verbosity level')

    return parser 
Example 4
Project: spy-ggp   Author: syllag   File: game_sender.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def treat_args():
    parser = argparse.ArgumentParser(description='Send command to server')

    parser.add_argument('command', metavar='COMMAND', choices=['get', 'start', 'stop','info', 'abort', 'play', 'play2'], help = 'start, stop, get, info, abort, play, play2')
    parser.add_argument('--url', help='provide URL of the server (by default http://localhost:8080)', default='http://localhost:8080')

    parser.add_argument('--kif', metavar='KIF_FILENAME', help='kiff filename, necessary for start and abort', type = argparse.FileType('r'), nargs = 1)
    parser.add_argument('--role', help='considered role (by default first role in file)', type = str, nargs = 1)
    parser.add_argument('--start_clock', help='start clock value in s (by default 60)', type = int, nargs = 1)
    parser.add_argument('--play_clock', help='play clock value in s (by default 10)', type = int, nargs = 1)
    parser.add_argument('--match_id', help='id of the considered match', type = str, nargs = 1)
    parser.add_argument('--play_content', help='play content', type = str, nargs = 1)

    args = parser.parse_args()

    return args 
Example 5
Project: recipes-py   Author: luci   File: __init__.py    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 6
Project: recipes-py   Author: luci   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def add_arguments(parser):
  parser.add_argument(
      '--final-state', type=argparse.FileType('wb'),
      help='Path to write the final build.proto state to (as binary PB).')
  parser.add_argument(
      '--build-proto-jsonpb', action='store_true',
      help=(
        'If specified, output build.proto datagrams as JSONPB instead of PB. '
        'Only for debugging.'
      ))

  def _launch(args):
    from .cmd import main
    try:
      return main(args)
    except RunBuildContractViolation as ex:
      LOG.fatal('"luciexe" protocol contract violation: %s', ex)
      return 1

  def _post(_error, _args):
    logging.basicConfig()

  parser.set_defaults(func=_launch, postprocess_func=_post) 
Example 7
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: Inject.py    GNU General Public License v3.0 6 votes vote down vote up
def add_options(self,options):
        options.add_argument("--js-url",type=str,
                help="Location of your (presumably) malicious Javascript.")
        options.add_argument("--html-url",type=str,
                help="Location of your (presumably) malicious HTML. Injected via hidden iframe.")
        options.add_argument("--html-payload",type=str,default="",
                help="String you would like to inject.")
        options.add_argument("--html-file",type=argparse.FileType('r'),default=None,
                help="File containing code you would like to inject.")
        options.add_argument("--match-str",type=str,default="</body>",
                help="String you would like to match and place your payload before. (</body> by default)")
        options.add_argument("--per-domain",action="store_true",
                help="Inject once per domain per client.")
        options.add_argument("--rate-limit",type=float,
                help="Inject once every RATE_LIMIT seconds per client.")
        options.add_argument("--count-limit",type=int,
                help="Inject only COUNT_LIMIT times per client.")
        options.add_argument("--preserve-cache",action="store_true",
                help="Don't kill the server/client caching.") 
Example 8
Project: MTSv   Author: FofanovLab   File: export.py    MIT License 6 votes vote down vote up
def _parse_type(typestr, argname):
    """Parses the type from a string. 

    :param typestr: a string coercible to a type or argparse.FileType. If None 
    or an empty string, the default is `str`.
    :param argname: the argument name (used for error reporting)
    :returns: the actual type found (i.e. `int`, `str`, argparse.FileType('w'))
    """
    if typestr == FILE_R:
        return argparse.FileType('r')
    elif typestr == FILE_W:
        return argparse.FileType('w')
    elif typestr:
        try:
            return getattr(builtins, typestr)
        except AttributeError:
            raise ValueError(
                "Invalid type specified for `{}`: {}"
                .format(argname, typestr)
            )
    else:
        return str 
Example 9
Project: NiujiaoDebugger   Author: MrSrc   File: tool.py    GNU General Public License v3.0 6 votes vote down vote up
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:
            obj = json.load(infile)
        except ValueError as e:
            raise SystemExit(e)
    with outfile:
        json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
        outfile.write('\n') 
Example 10
Project: aiotunnel   Author: codepr   File: cli.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_parser():
    parser = argparse.ArgumentParser(description='aiotunnel CLI aiotunnels')
    parser.add_argument('subcommand', help='Runtime mode, can be either client or server')
    parser.add_argument('--file', '-f', nargs='?',
                        type=argparse.FileType('r'), help='Configuration file')
    parser.add_argument('--verbose', '-v', action='store_true',
                        default=False, help='Run with more logs')
    parser.add_argument('--reverse', '-r', action='store_true',
                        help='Run in reverse mode e.g. client connect to the '
                        'service to expose and ask the server to open a port')
    parser.add_argument('--client', '-c', action='store_true', help='Run in client mode')
    parser.add_argument('--addr', '-a', action='store', help='Set address to listen to')
    parser.add_argument('--port', '-p', action='store', help='Set the port to open')
    parser.add_argument('--target-addr', '-A', action='store', help='Set the target to expose/reach')
    parser.add_argument('--target-port', '-P', action='store', help='Set the port for target-addr')
    parser.add_argument('--server-addr', '-sa', action='store', help='Set the target address')
    parser.add_argument('--server-port', '-sp', action='store', help='Set the target port')
    parser.add_argument('--ca', action='store', help='Set the cert. authority file')
    parser.add_argument('--cert', action='store', help='Set the crt file for SSL/TLS encryption')
    parser.add_argument('--key', action='store', help='Set the key file for SSL/TLS encryption')
    return parser 
Example 11
Project: rnftools   Author: karel-brinda   File: scripts.py    MIT License 6 votes vote down vote up
def add_curesim_parser(subparsers, subcommand, help, description):
    parser_curesim2rnf = subparsers.add_parser(subcommand, help=help, description=description)

    parser_curesim2rnf.set_defaults(func=curesim2rnf)

    parser_curesim2rnf.add_argument(
        '-c',
        '--curesim-fastq',
        type=argparse.FileType('r'),
        metavar='file',
        dest='curesim_fastq_fo',
        required=True,
        help='CuReSim FASTQ file (- for standard input).',
    )

    _add_shared_params(parser_curesim2rnf, unmapped_switcher=False)


################################
# DWGSIM
################################ 
Example 12
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_r(self):
        type = argparse.FileType('r')
        self.assertEqual("FileType('r')", repr(type)) 
Example 13
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_wb_1(self):
        type = argparse.FileType('wb', 1)
        self.assertEqual("FileType('wb', 1)", repr(type)) 
Example 14
Project: anishot   Author: sourcerer-io   File: __main__.py    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 15
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: chardetect.py    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 16
Project: MFEprimer_linux   Author: nick-youngblut   File: MFEprimerParser.py    MIT License 5 votes vote down vote up
def get_opt():
    '''Get options'''
    global args
    parser = argparse.ArgumentParser(description='Descriptions about the script.')
    parser.add_argument('-i', '--infile', nargs='?', type=argparse.FileType('r'),
		    default=sys.stdin, help='Input file to be processed', required=True)
    parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'),
		    default=sys.stdout, help='Output file name for storing the results')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
    args = parser.parse_args() 
Example 17
Project: MFEprimer_linux   Author: nick-youngblut   File: FastaRemoveRedundant.py    MIT License 5 votes vote down vote up
def get_opt():
    '''Get options'''
    global args
    parser = argparse.ArgumentParser(description='Remove the same sequences in the FASTA files')
    parser.add_argument('-i', '--infile', nargs='?', type=argparse.FileType('r'),
		    default=sys.stdin, help='Input file to be processed', required=True)
    parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'),
		    default=sys.stdout, help='Output file name for storing the results')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
    args = parser.parse_args() 
Example 18
Project: MFEprimer_linux   Author: nick-youngblut   File: chilli.py    MIT License 5 votes vote down vote up
def get_opt():
    '''Get options'''
    global args
    parser = argparse.ArgumentParser(description='Descriptions about the script.')
    parser.add_argument('-i', '--infile', nargs='?', type=argparse.FileType('r'),
		    default=sys.stdin, help='Input file to be processed', required=True)
    parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'),
		    default=sys.stdout, help='Output file name for storing the results')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
    args = parser.parse_args() 
Example 19
Project: sic   Author: Yanixos   File: chardetect.py    GNU 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",
        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 20
Project: bigquerylayers   Author: smandaric   File: chardetect.py    GNU 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 21
Project: AshsSDK   Author: thehappydinoa   File: chardetect.py    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 22
Project: AshsSDK   Author: thehappydinoa   File: chardetect.py    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: Kitsu.Bundle   Author: AeonLucid   File: chardetect.py    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: openaps-glucosetools   Author: loudnate   File: __init__.py    MIT License 5 votes vote down vote up
def _opt_json_file(filename):
    """Parses a filename as JSON input if defined

    :param filename: The path to the file to parse
    :type filename: basestring
    :return: A decoded JSON object if a filename was specified
    :rtype: dict|list|NoneType
    """
    if filename:
        return json.load(argparse.FileType('r')(filename)) 
Example 25
Project: openaps-glucosetools   Author: loudnate   File: __init__.py    MIT License 5 votes vote down vote up
def get_program(self, params):
        """Parses params into history parser constructor arguments

        :param params:
        :type params: dict
        :return:
        :rtype: tuple(list, dict)
        """
        return [json.load(argparse.FileType('r')(params['infile']))], dict()


# noinspection PyPep8Naming 
Example 26
Project: strace-process-tree   Author: mgedmin   File: strace_process_tree.py    GNU General Public License v2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(
        description="""
            Read strace -f output and produce a process tree.

            Recommended strace options for best results:

                strace -f -ttt -e trace=process -s 1024 -o FILENAME COMMAND
            """)
    parser.add_argument('--version', action='version', version=__version__)
    parser.add_argument('-c', '--color', action='store_true', default=None,
                        help='force color output')
    parser.add_argument('-C', '--no-color', action='store_false', dest='color',
                        help='disable color output')
    parser.add_argument('-U', '--unicode', action='store_true', default=None,
                        help='force Unicode output')
    parser.add_argument('-A', '--ascii', action='store_false', dest='unicode',
                        help='force ASCII output')
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='more verbose output')
    parser.add_argument('filename', type=argparse.FileType('r'),
                        help='strace log to parse (use - to read stdin)')
    args = parser.parse_args()

    mogrifier = simplify_syscall if args.verbose else extract_command_line

    tree = parse_stream(events(args.filename), mogrifier)

    theme = Theme(color=args.color, unicode=args.unicode)
    print(tree.format(theme).rstrip()) 
Example 27
Project: jawfish   Author: war-and-code   File: chardetect.py    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 28
Project: cssdiff   Author: podhmo   File: __init__.py    MIT License 5 votes vote down vote up
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("src", type=argparse.FileType('r'))
    parser.add_argument("dst", type=argparse.FileType('r'))
    parser.add_argument("--verbose", action="store_true", default=False)
    args = parser.parse_args()
    s0 = load(args.src, verbose=args.verbose)
    s1 = load(args.dst, verbose=args.verbose)
    print(s0.difference(s1).to_string()) 
Example 29
Project: Repobot   Author: Desgard   File: chardetect.py    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 30
Project: Repobot   Author: Desgard   File: chardetect.py    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 31
Project: lena   Author: coingraham   File: chardetect.py    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 32
Project: gist-alfred   Author: danielecook   File: chardetect.py    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 33
Project: me-ica   Author: ME-ICA   File: argparse_to_json.py    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 34
Project: rebel-framework   Author: reb311ion   File: chardetect.py    GNU 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 35
Project: rebel-framework   Author: reb311ion   File: chardetect.py    GNU 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",
        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 36
Project: bamkit   Author: hall-lab   File: bamheadrg.py    MIT License 5 votes vote down vote up
def get_args():
    parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="\
bamheadrg.py\n\
author: " + __author__ + "\n\
version: " + __version__ + "\n\
description: Inject readgroup info")
    parser.add_argument('-r', '--readgroup', default=None, required=False, help='Read group(s) to extract (comma separated)')
    parser.add_argument('-d', '--donor', type=str, required=True, help='Donor BAM/SAM file to extract read group info')
    parser.add_argument('-S', '--donor_is_sam', required=False, action='store_true', help='Donor file is SAM')
    parser.add_argument('recipient', nargs='?', type=argparse.FileType('r'), default=None,
                        help='SAM file to inject header lines into. If \'-\' or absent then defaults to stdin.')

    # parse the arguments
    args = parser.parse_args()

    # if no input, check if part of pipe and if so, read stdin.
    if args.recipient == None:
        if sys.stdin.isatty():
            parser.print_help()
            exit(1)
        else:
            args.recipient = sys.stdin

    # send back the user input
    return args

# extract read group information from header of original bam 
Example 37
Project: bamkit   Author: hall-lab   File: bamfixflags.py    MIT License 5 votes vote down vote up
def get_args():
    parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="\
bamfixflags.py\n\
author: " + __author__ + "\n\
version: " + __version__ + "\n\
description: filter readgroup(s) from a BAM file")
    parser.add_argument('-i', '--input', metavar='BAM', required=False, help='Input BAM file')
    parser.add_argument('-l', '--lib_info', metavar='FILE', dest='lib_info_file', type=argparse.FileType('r'), required=True, default=None, help='SVTyper JSON file of library information')
    parser.add_argument('-n', metavar='INT', type=int, default=None, required=False, help='Output first n alignments and quit')
    parser.add_argument('-S', required=False, action='store_true', help='Input is SAM format')
    parser.add_argument('-b', required=False, action='store_true', help='Output BAM format')
    parser.add_argument('-u', required=False, action='store_true', help='Output uncompressed BAM format (implies -b)')

    # parse the arguments
    args = parser.parse_args()

    # bail if no BAM file
    if args.input is None:
        if sys.stdin.isatty():
            parser.print_help()
            exit(1)
    
    # send back the user input
    return args

# ============================================
# driver
# ============================================ 
Example 38
Project: bamkit   Author: hall-lab   File: bamtofastq.py    MIT License 5 votes vote down vote up
def get_args():
    parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="\
bamtofastq.py\n\
author: " + __author__ + "\n\
version: " + __version__ + "\n\
description: Convert a coordinate sorted BAM file to FASTQ\n\
             (ignores unpaired reads)")
    # parser.add_argument('-i', '--input', metavar='BAM', required=False, help='Input BAM file')
    parser.add_argument('-r', '--readgroup', metavar='STR', default=None, required=False, help='Read group(s) to extract (comma separated)')
    parser.add_argument('-n', '--rename', required=False, action='store_true', help='Rename reads')
    parser.add_argument('-S', '--is_sam', required=False, action='store_true', help='Input is SAM format')
    parser.add_argument('-H', '--header', metavar='FILE', type=argparse.FileType('w'), default=None, required=False,
                        help='Write BAM header to file')
    parser.add_argument('input', metavar='BAM', nargs='*', type=str,
                        help='Input BAM file(s). If absent then defaults to stdin.')

    # parse the arguments
    args = parser.parse_args()

    # bail if no BAM file
    if len(args.input) == 0:
        if sys.stdin.isatty():
            parser.print_help()
            exit(1)
        else:
            args.input = [None]
    
    # send back the user input
    return args 
Example 39
Project: JukeBox   Author: gauravsarkar97   File: chardetect.py    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 40
Project: misp42splunk   Author: remg427   File: chardetect.py    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",
        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 41
Project: misp42splunk   Author: remg427   File: chardetect.py    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",
        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 42
Project: recipes-py   Author: luci   File: __init__.py    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 43
Project: chattR   Author: patrickstocklin   File: chardetect.py    GNU General Public License v2.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",
        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 44
Project: keepaneyeon   Author: mmcloughlin   File: cli.py    MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(
        description='Fetch URLs and record changes')
    parser.add_argument('config', action='store', type=argparse.FileType('r'),
            default=sys.stdin, help='configuration file')
    args = parser.parse_args()

    cfg = keepaneyeon.config.load(args.config)
    for target in cfg['targets']:
        target.fetch() 
Example 45
Project: princess   Author: MeHelmy   File: phasing_report_update_vcf.py    MIT License 5 votes vote down vote up
def get_args():
    parser = argparse.ArgumentParser(epilog="%(prog)s version 0.01. use command -h for info.",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     description='Produce phasing report',
                                     add_help=True, )
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.01')
    # parser.add_argument('input', help='Input file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
    # parser.add_argument('output', help='Output file', nargs="?", type=argparse.FileType('w'), default=sys.stdout)

    # parser.add_argument('input', nargs='?', help="Phased vcf file",
    #                          type=argparse.FileType('r'),
    #                          default=sys.stdin)
    # parser.add_argument('output', nargs='?', help="Output file if no file result will be directed to stander output",
    #                              type=argparse.FileType('w+'),
    #                              default=sys.stdout)
    parser.add_argument('-i', '--input', nargs='?', help="Phased vcf file", required=True)
    parser.add_argument('-o', '--output', nargs='?', help="Output file for blocks", required=True)
    parser.add_argument('-s', '--stat', nargs='?', help="Output statistics file for phased datat", required=True)
    parser.add_argument("-u", '--update_snps',  help="Output updated snp file", required=True)
    parser.add_argument('-t', '--tolerance', help="Percent of tolerance.", type=int, action='store', default=5)
    parser.add_argument('-n', '--min_snps', help="Minimum Number of SNPs per block.", type=int, action='store', default=10)

    parser.set_defaults(func=phase_filtering)
    args = parser.parse_args()
    if 'func' in args:
        args.func(args)
    else:
        parser.print_help() 
Example 46
Project: princess   Author: MeHelmy   File: update_sv_hp_ps.py    MIT License 5 votes vote down vote up
def get_args():
    parser = argparse.ArgumentParser(epilog="%(prog)s version 0.01. use command -h for info.",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     description='Produce phasing report',
                                     add_help=True, )
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.01')
    # parser.add_argument('input', help='Input file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
    # parser.add_argument('output', help='Output file', nargs="?", type=argparse.FileType('w'), default=sys.stdout)

    parser.add_argument('input', nargs='?', help="Structural variant vcf file",
                             type=argparse.FileType('r'),
                             default=sys.stdin)
    parser.add_argument('hp', nargs='?', help="tab delimeted read\thp\tps file",
                             type=argparse.FileType('r'))
    parser.add_argument('output', nargs='?', help="Output file, PS and HP will be added.",
                                 type=argparse.FileType('w+'),
                                 default=sys.stdout)

    parser.set_defaults(func=update_vcf)

    # if not argument print help.
    if len(sys.argv) == 1 and  sys.stdin.isatty():  # sys.stdin.isatty() returns false if there's something in stdin
         parser.print_help(sys.stderr)
         sys.exit(1)

    args = parser.parse_args()


    if 'func' in args:
        args.func(args)
    else:
        parser.print_help() 
Example 47
Project: mergevcf   Author: ljdursi   File: __init__.py    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) 
Example 48
Project: swift-idl   Author: safx   File: json2idl.py    MIT License 5 votes vote down vote up
def parseArgs():
    parser = argparse.ArgumentParser(description='Swift source generator from JSON')
    parser.add_argument('jsonfile', type=argparse.FileType('r'), nargs='?', help='json to parse', default=sys.stdin)
    parser.add_argument('-c', '--classname', type=str, default=None, help='class name')
    parser.add_argument('-p', '--parameter', type=str, default=None, help='annotation parameter')
    parser.add_argument('-a', '--apikit', action='store_true', help='APIKit')
    return parser.parse_args() 
Example 49
Project: aws_python_messenger   Author: AdamSpannbauer   File: chardetect.py    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 50
Project: aws_python_messenger   Author: AdamSpannbauer   File: chardetect.py    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))