Exemplo n.º 1
0
def main(verbose, interactive, multiline, serve, batch, test, fname='',
         *extra):
    "Runner for plac tools, plac batch files and plac tests"
    baseparser = plac.parser_from(main)
    if not fname:
        baseparser.print_help()
    elif sys.argv[1] == fname:  # script mode
        plactool = plac.import_main(fname)
        plactool.prog = os.path.basename(sys.argv[0]) + ' ' + fname
        out = plac.call(plactool, sys.argv[2:], eager=False)
        if plac.iterable(out):
            for output in out:
                print(output)
        else:
            print(out)
    elif interactive or multiline or serve:
        plactool = plac.import_main(fname, *extra)
        plactool.prog = ''
        i = plac.Interpreter(plactool)
        if interactive:
            i.interact(verbose=verbose)
        elif multiline:
            i.multiline(verbose=verbose)
        elif serve:
            i.start_server(serve)
    elif batch:
        run((fname,) + extra, 'execute', verbose)
    elif test:
        run((fname,) + extra, 'doctest', verbose)
        print('run %s plac test(s)' % (len(extra) + 1))
    else:
        baseparser.print_usage()
Exemplo n.º 2
0
def plac_call(obj, arglist=None, eager=True, version=None):
    """
    If obj is a function or a bound method, parse the given arglist
    by using the parser inferred from the annotations of obj
    and call obj with the parsed arguments.
    If obj is an object with attribute .commands, dispatch to the
    associated subparser.
    """
    assert HAS_PLAC, '`plac` package is not available, please install it'
    if hasattr(obj, '_plac_func'):
        # `plac` needs the annotated original function (w/ __annotations__ attributes)
        if arglist is None:
            arglist = sys.argv[1:]
        if not inspect.isfunction(obj):
            arglist = ['_trick_arg0_'] + arglist
            obj._meta['is_function'] = False
        parser = plac.parser_from(obj._plac_func)
        if version:
            parser.add_argument('--version',
                                '-v',
                                action='version',
                                version=version)
        # below: trick so that `plac` will consume the command-line arguments but still use the `defaults` wrapper
        parser.func = obj
        cmd, result = parser.consume(arglist)
        if plac.iterable(result) and eager:  # listify the result
            return list(result)
        return result
    else:
        return plac.call(obj, arglist=arglist, eager=eager, version=version)
Exemplo n.º 3
0
def main(verbose, interactive, multiline, serve, batch, test, fname=None,
         *extra):
    "Runner for plac tools, plac batch files and plac tests"
    baseparser = plac.parser_from(main)
    if fname is None:
        baseparser.print_help()
    elif sys.argv[1] == fname: # script mode
        plactool = plac.import_main(fname)
        plactool.prog = os.path.basename(sys.argv[0]) + ' ' + fname
        out = plac.call(plactool, sys.argv[2:], eager=False)
        if plac.iterable(out):
            for output in out:
                print(output)
        else:
            print(out)
    elif interactive or multiline or serve:
        plactool = plac.import_main(fname, *extra)
        plactool.prog = ''
        i = plac.Interpreter(plactool)
        if interactive:
            i.interact(verbose=verbose)
        elif multiline:
            i.multiline(verbose=verbose)
        elif serve:
            i.start_server(serve)
    elif batch:
        run((fname,) + extra, 'execute', verbose)
    elif test:
        run((fname,) + extra, 'doctest', verbose)
        print('run %s plac test(s)' % (len(extra) + 1))
    else:
        baseparser.print_usage()
 def __init__(self, func: Callable):
     super().__init__()
     self._func = func
     self._run_lock = Lock()
     self._signature = inspect.signature(self._func)
     _arg_parser = plac.parser_from(self._func)
     self._argspec = _arg_parser.argspec
     self._num_request = 0
Exemplo n.º 5
0
def get_plac_parser(depth=1):
    """Get the plac-generated parser for the calling function.

With optional arg 'depth', get the parser for the function that far up the call stack."""
    func = _giveupthefunc(depth=depth+1)
    if func:
        return plac.parser_from(func)
    else:
        raise ValueError("Could not find function at specified depth")
Exemplo n.º 6
0
def get_plac_parser(depth=1):
    """Get the plac-generated parser for the calling function.

With optional arg 'depth', get the parser for the function that far up the call stack."""
    func = _giveupthefunc(depth=depth + 1)
    if func:
        return plac.parser_from(func)
    else:
        raise ValueError("Could not find function at specified depth")
Exemplo n.º 7
0
def call(obj, arglist=sys.argv[1:], eager=True, config=None,
         default_section=None, gnu=True):
    if gnu:
        plac.ArgumentParser.add_argument = add_gnu_argument

    if config is None:
        return plac.call(obj, arglist=arglist, eager=eager)

    argparser = plac.parser_from(obj)
    argnames = argparser.argspec.args
    defaults = argparser.argspec.defaults

    cp = config_parser_from(obj, config, default_section)

    cfg = dict(zip_longest(argnames, defaults))
    ini_values = _read_config(cp, config, default_section)

    for k in obj.__annotations__.keys():
        a = plac.Annotation.from_(obj.__annotations__[k])
        if a.type and k in ini_values:
            if a.type is type(True):
                try:
                    ini_values[k] = cp._convert_to_boolean(ini_values[k])
                except ValueError:
                    argparser.print_usage(sys.stderr)
                    _print_exit(
                        "{}: error: {}={} failed conversion to <type 'bool'> in:\n{}\n".format(
                            argparser.prog, k, ini_values[k], config))
            else:
                try:
                    ini_values[k] = a.type(ini_values[k])
                except ValueError:
                    argparser.print_usage(sys.stderr)
                    _print_exit(
                        '{}: error: {}={} failed conversion to {} in:\n{}\n'.format(
                            argparser.prog, k, ini_values[k], a.type, config))

    cfg.update(ini_values)

    if sys.version >= '3':
        items = cfg.items()
    else:
        items = cfg.iteritems()
    argparser.set_defaults(**dict((k, v) for k, v in items))
    cmd, result = argparser.consume(arglist)

    if plac.iterable(result) and eager: # listify the result
        return list(result)
    return result
Exemplo n.º 8
0
def check_help(name):
    sys.argv[0] = name + '.py'  # avoid issue with pytest
    plac_core._parser_registry.clear()  # makes different imports independent
    try:
        try:
            main = plac.import_main(name + '.py')
        except SyntaxError:
            if sys.version < '3':  # expected for Python 2.X
                return
            else:  # not expected for Python 3.X
                raise
        p = plac.parser_from(main)
        expected = fix_today(open(name + '.help').read()).strip()
        got = p.format_help().strip()
        assert got == expected, got
    finally:
        sys.argv[0] = sys_argv0
Exemplo n.º 9
0
def check_help(name):
    sys.argv[0] = name + '.py'  # avoid issue with nosetests
    plac_core._parser_registry.clear()  # makes different imports independent
    try:
        try:
            main = plac.import_main(name + '.py')
        except SyntaxError:
            if sys.version < '3':  # expected for Python 2.X
                return
            else:  # not expected for Python 3.X
                raise
        p = plac.parser_from(main)
        expected = fix_today(open(name + '.help').read()).strip()
        got = p.format_help().strip()
        assert got == expected, got
    finally:
        sys.argv[0] = sys_argv0
Exemplo n.º 10
0
def parser_from(f, **kw):
    f.__annotations__ = kw
    return plac.parser_from(f)
Exemplo n.º 11
0
def parser_from(f, **kw):
    f.__annotations__ = kw
    return plac.parser_from(f)
Exemplo n.º 12
0
    ip_p = IP()
    udp_p = UDP()
    dns_p = DNS()
    dns_qd = DNSQR()

    if iface is None: iface = scapy.config.conf.iface
    if src is not None: ip_p.src = src
    if dst is not None: ip_p.dst = dst
    if sport is not None: udp_p.sport = sport
    if dport is not None: udp_p.dport = dport

    for field in dns_fuzz_fields:
        if l[field] is not None:
            dns_p.setfieldval(field, l[field])

    if qname is not None: dns_qd.qname = qname
    if qtype is not None: dns_qd.qtype = qtype
    if qclass is not None: dns_qd.qclass = qclass

    dns_p.qd = fuzz(dns_qd)
    pkt = ip_p/udp_p/fuzz(dns_p)

    ans = sr1(pkt)
    print ans.show()


if __name__ == '__main__':
    parser = plac.parser_from(main)
    sys.exit(plac.call(main))

Exemplo n.º 13
0
 def help(self, name):
     print(plac.parser_from(self).help_cmd(name))
Exemplo n.º 14
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self._signature = self._conn.root.signature()
     self._argspec = self._conn.root.argspec()
     with hijack_argspec(self._argspec):
         self._argparser = plac.parser_from(self.run)