python类dumps()的实例源码

gen_library_compressed_string.py 文件源码 项目:OSPTF 作者: xSploited 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_encoded_library_string(arch):
    filepath=None
    if arch=="x86":
        filepath=os.path.join("resources","libraryx86.zip")
    elif arch=="x64":
        filepath=os.path.join("resources","libraryx64.zip")
    else:
        raise Exception("unknown arch %s"%arch)
    f = StringIO.StringIO()
    f.write(open(filepath, "rb").read())

    zip = zipfile.ZipFile(f)

    modules = dict([(z.filename, zip.open(z.filename,).read()) for z in zip. infolist() if os.path.splitext(z.filename)[1] in [".py",".pyd",".dll",".pyc",".pyo"]])

    return zlib.compress(marshal.dumps(modules),9)
1b_sirene_geo.py 文件源码 项目:geocodage-spd 作者: cquest 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def geocode(api, params, l4):
    params['autocomplete']=0
    params['q'] = params['q'].strip()
    try:
        r = requests.get(api, params)
        j = json.loads(r.text)
        global geocode_count
        geocode_count += 1
        if 'features' in j and len(j['features'])>0:
            j['features'][0]['l4'] = l4
            return(j['features'][0])
        else:
            return(None)
    except:
        print(json.dumps({'action':'erreur','params': params, 'l4': l4}))
        return(None)
serializers.py 文件源码 项目:MIT-Thesis 作者: alec-heif 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def dump_stream(self, iterator, stream):
        batch, best = 1, self.bestSize
        iterator = iter(iterator)
        while True:
            vs = list(itertools.islice(iterator, batch))
            if not vs:
                break

            bytes = self.serializer.dumps(vs)
            write_int(len(bytes), stream)
            stream.write(bytes)

            size = len(bytes)
            if size < best:
                batch *= 2
            elif size > best * 10 and batch > 1:
                batch //= 2
tools.py 文件源码 项目:sahriswiki 作者: prologic 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _on_request(self, event, request, response):
        if request.path in ("/+login", "/+logout"):
            return

        repo = short(self.environ.storage.repo_node())
        sess = md5(dumps(request.session)).hexdigest()
        config = md5(dumps(self.environ.config.copy())).hexdigest()
        version = sahriswiki.__version__

        etag = "%s/%s/%s/%s" % (repo, sess, config, version)

        response.headers.add_header("ETag", etag)
        response = validate_etags(request, response)
        if response:
            event.stop()
            return response
gen_library_compressed_string.py 文件源码 项目:pupy 作者: ru-faraon 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_encoded_library_string(arch):
    filepath=None
    if arch=="x86":
        filepath=os.path.join("resources","libraryx86.zip")
    elif arch=="x64":
        filepath=os.path.join("resources","libraryx64.zip")
    else:
        raise Exception("unknown arch %s"%arch)
    f = StringIO.StringIO()
    f.write(open(filepath, "rb").read())

    zip = zipfile.ZipFile(f)

    modules = dict([(z.filename, zip.open(z.filename,).read()) for z in zip. infolist() if os.path.splitext(z.filename)[1] in [".py",".pyd",".dll",".pyc",".pyo"]])

    return zlib.compress(marshal.dumps(modules),9)
dal.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def as_json(self, mode='object', default=None):
        """
        serializes the rows to a JSON list or object with objects
        mode='object' is not implemented (should return a nested
        object structure)
        """

        items = [record.as_json(mode=mode, default=default,
                                serialize=False,
                                colnames=self.colnames) for
                 record in self]

        if have_serializers:
            return serializers.json(items,
                                    default=default or
                                    serializers.custom_json)
        elif simplejson:
            return simplejson.dumps(items)
        else:
            raise RuntimeError("missing simplejson")

    # for consistent naming yet backwards compatible
test_marshal.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_floats(self):
        # Test a few floats
        small = 1e-25
        n = sys.maxsize * 3.7e250
        while n > small:
            for expected in (-n, n):
                self.helper(float(expected))
            n /= 123.4567

        f = 0.0
        s = marshal.dumps(f, 2)
        got = marshal.loads(s)
        self.assertEqual(f, got)
        # and with version <= 1 (floats marshalled differently then)
        s = marshal.dumps(f, 1)
        got = marshal.loads(s)
        self.assertEqual(f, got)

        n = sys.maxsize * 3.7e-250
        while n < small:
            for expected in (-n, n):
                f = float(expected)
                self.helper(f)
                self.helper(f, 1)
            n *= 123.4567
test_marshal.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_recursion_limit(self):
        # Create a deeply nested structure.
        head = last = []
        # The max stack depth should match the value in Python/marshal.c.
        if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
            MAX_MARSHAL_STACK_DEPTH = 1500
        else:
            MAX_MARSHAL_STACK_DEPTH = 2000
        for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
            last.append([0])
            last = last[-1]

        # Verify we don't blow out the stack with dumps/load.
        data = marshal.dumps(head)
        new_head = marshal.loads(data)
        # Don't use == to compare objects, it can exceed the recursion limit.
        self.assertEqual(len(new_head), len(head))
        self.assertEqual(len(new_head[0]), len(head[0]))
        self.assertEqual(len(new_head[-1]), len(head[-1]))

        last.append([0])
        self.assertRaises(ValueError, marshal.dumps, head)
rpc.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def putmessage(self, message):
        self.debug("putmessage:%d:" % message[0])
        try:
            s = pickle.dumps(message)
        except pickle.PicklingError:
            print("Cannot pickle:", repr(message), file=sys.__stderr__)
            raise
        s = struct.pack("<i", len(s)) + s
        while len(s) > 0:
            try:
                r, w, x = select.select([], [self.sock], [])
                n = self.sock.send(s[:BUFSIZE])
            except (AttributeError, TypeError):
                raise IOError("socket no longer exists")
            except socket.error:
                raise
            else:
                s = s[n:]
generic_utils.py 文件源码 项目:deep-learning-keras-projects 作者: jasmeetsb 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def func_dump(func):
    """Serializes a user defined function.

    # Arguments
        func: the function to serialize.

    # Returns
        A tuple `(code, defaults, closure)`.
    """
    code = marshal.dumps(func.__code__).decode('raw_unicode_escape')
    defaults = func.__defaults__
    if func.__closure__:
        closure = tuple(c.cell_contents for c in func.__closure__)
    else:
        closure = None
    return code, defaults, closure
stdlib_compile.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def compileAndWrite(in_path, out_path, compile_func):
  #print(stdlib_comp, file=sys.stderr)

  with open(in_path) as f:
    co = compile_func(f.read(), in_path, 'exec')

  #print(co, file=sys.stderr)

  h = getPycHeader(in_path)
  with open(out_path, 'w') as out_f:
    out_f.write(h)

    s = marshal.dumps(co)
    #m = hashlib.md5()
    #m.update(s)
    #print(m.hexdigest(), file=sys.stderr)

    out_f.write(s)
test_marshal.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_recursion_limit(self):
        # Create a deeply nested structure.
        head = last = []
        # The max stack depth should match the value in Python/marshal.c.
        if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
            MAX_MARSHAL_STACK_DEPTH = 1000
        else:
            MAX_MARSHAL_STACK_DEPTH = 2000
        for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
            last.append([0])
            last = last[-1]

        # Verify we don't blow out the stack with dumps/load.
        data = marshal.dumps(head)
        new_head = marshal.loads(data)
        # Don't use == to compare objects, it can exceed the recursion limit.
        self.assertEqual(len(new_head), len(head))
        self.assertEqual(len(new_head[0]), len(head[0]))
        self.assertEqual(len(new_head[-1]), len(head[-1]))

        last.append([0])
        self.assertRaises(ValueError, marshal.dumps, head)
test_marshal.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_recursion_limit(self):
        # Create a deeply nested structure.
        head = last = []
        # The max stack depth should match the value in Python/marshal.c.
        if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
            MAX_MARSHAL_STACK_DEPTH = 1000
        else:
            MAX_MARSHAL_STACK_DEPTH = 2000
        for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
            last.append([0])
            last = last[-1]

        # Verify we don't blow out the stack with dumps/load.
        data = marshal.dumps(head)
        new_head = marshal.loads(data)
        # Don't use == to compare objects, it can exceed the recursion limit.
        self.assertEqual(len(new_head), len(head))
        self.assertEqual(len(new_head[0]), len(head[0]))
        self.assertEqual(len(new_head[-1]), len(head[-1]))

        last.append([0])
        self.assertRaises(ValueError, marshal.dumps, head)
seccomp.py 文件源码 项目:orizonhub 作者: gumblex 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _child_main(self):
        self.host.close()
        for fd in map(int, os.listdir('/proc/self/fd')):
            if fd != self.child.fileno():
                try:
                    os.close(fd)
                except OSError:
                    pass

        resource.setrlimit(resource.RLIMIT_CPU, (1, 1))
        prctl.set_seccomp(True)
        while True:
            sz, = struct.unpack('>L', read_exact(self.child, 4))
            doc = marshal.loads(read_exact(self.child, sz))
            if doc['cmd'] == 'eval':
                resp = self.do_eval(doc)
            elif doc['cmd'] == 'exit':
                _exit(0)
            goobs = marshal.dumps(resp)
            write_exact(self.child, struct.pack('>L', len(goobs)))
            write_exact(self.child, goobs)
tf-keras-skeleton.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def func_dump(func):
          """Serializes a user defined function.

          Arguments:
              func: the function to serialize.

          Returns:
              A tuple `(code, defaults, closure)`.
          """
          code = marshal.dumps(func.__code__).decode('raw_unicode_escape')
          defaults = func.__defaults__
          if func.__closure__:
            closure = tuple(c.cell_contents for c in func.__closure__)
          else:
            closure = None
          return code, defaults, closure
test_marshal.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_floats(self):
        # Test a few floats
        small = 1e-25
        n = sys.maxsize * 3.7e250
        while n > small:
            for expected in (-n, n):
                self.helper(float(expected))
            n /= 123.4567

        f = 0.0
        s = marshal.dumps(f, 2)
        got = marshal.loads(s)
        self.assertEqual(f, got)
        # and with version <= 1 (floats marshalled differently then)
        s = marshal.dumps(f, 1)
        got = marshal.loads(s)
        self.assertEqual(f, got)

        n = sys.maxsize * 3.7e-250
        while n < small:
            for expected in (-n, n):
                f = float(expected)
                self.helper(f)
                self.helper(f, 1)
            n *= 123.4567
test_marshal.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_recursion_limit(self):
        # Create a deeply nested structure.
        head = last = []
        # The max stack depth should match the value in Python/marshal.c.
        if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
            MAX_MARSHAL_STACK_DEPTH = 1500
        else:
            MAX_MARSHAL_STACK_DEPTH = 2000
        for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
            last.append([0])
            last = last[-1]

        # Verify we don't blow out the stack with dumps/load.
        data = marshal.dumps(head)
        new_head = marshal.loads(data)
        # Don't use == to compare objects, it can exceed the recursion limit.
        self.assertEqual(len(new_head), len(head))
        self.assertEqual(len(new_head[0]), len(head[0]))
        self.assertEqual(len(new_head[-1]), len(head[-1]))

        last.append([0])
        self.assertRaises(ValueError, marshal.dumps, head)
__init__.py 文件源码 项目:covertutils 作者: operatorequals 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __form_stage_from_function( init, work ) :
    ret = {}
    dict_ = {'init' : init, 'work' : work}
    try:                    # Python 3
        code = {'init' : init.__code__, 'work' : work.__code__}
    except AttributeError:  # Python 2
        code = {'init' : init.func_code, 'work' : work.func_code}
    ret['object'] = dict_
    ret['python'] = code
    try :
        marshaled = marshal.dumps(code)
    except ValueError:
        marshaled = None

    try :
        import dill
        dilled = dill.dumps(code)
    except ImportError:
        dilled = None
    ret['dill'] = dilled
    ret['marshal'] = marshaled

    return ret
pickle.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def dumps(obj, protocol=None):
    file = StringIO()
    Pickler(file, protocol).dump(obj)
    return file.getvalue()
bccache.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def marshal_dump(code, f):
        if isinstance(f, file):
            marshal.dump(code, f)
        else:
            f.write(marshal.dumps(code))
bccache.py 文件源码 项目:swjtu-pyscraper 作者: Desgard 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def marshal_dump(code, f):
        if isinstance(f, file):
            marshal.dump(code, f)
        else:
            f.write(marshal.dumps(code))
bccache.py 文件源码 项目:sublime-text-3-packages 作者: nickjj 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def marshal_dump(code, f):
        if isinstance(f, file):
            marshal.dump(code, f)
        else:
            f.write(marshal.dumps(code))
bccache.py 文件源码 项目:zanph 作者: zanph 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def marshal_dump(code, f):
        if isinstance(f, file):
            marshal.dump(code, f)
        else:
            f.write(marshal.dumps(code))
pickle.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def dumps(obj, protocol=None):
    file = StringIO()
    Pickler(file, protocol).dump(obj)
    return file.getvalue()
forkedfunc.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def _child(self, nice_level, child_on_start, child_on_exit):
        # right now we need to call a function, but first we need to
        # map all IO that might happen
        sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT)
        sys.stderr = stderr = get_unbuffered_io(2, self.STDERR)
        retvalf = self.RETVAL.open("wb")
        EXITSTATUS = 0
        try:
            if nice_level:
                os.nice(nice_level)
            try:
                if child_on_start is not None:
                    child_on_start()
                retval = self.fun(*self.args, **self.kwargs)
                retvalf.write(marshal.dumps(retval))
                if child_on_exit is not None:
                    child_on_exit()
            except:
                excinfo = py.code.ExceptionInfo()
                stderr.write(str(excinfo._getreprcrash()))
                EXITSTATUS = self.EXITSTATUS_EXCEPTION
        finally:
            stdout.close()
            stderr.close()
            retvalf.close()
        os.close(1)
        os.close(2)
        os._exit(EXITSTATUS)
uwsgi_features.py 文件源码 项目:pyprometheus 作者: Lispython 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def serialize_key(self, key):
        try:
            return self._keys_cache[key]
        except KeyError:
            self._keys_cache[key] = val = marshal.dumps(key)
            return val
bccache.py 文件源码 项目:Sci-Finder 作者: snverse 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def marshal_dump(code, f):
        if isinstance(f, file):
            marshal.dump(code, f)
        else:
            f.write(marshal.dumps(code))
bccache.py 文件源码 项目:Sci-Finder 作者: snverse 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def marshal_dump(code, f):
        if isinstance(f, file):
            marshal.dump(code, f)
        else:
            f.write(marshal.dumps(code))
concrete.py 文件源码 项目:amphitrite 作者: cosine0 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def run_to_condition(self, function, include_this_address=False, commit_next_instruction_to_hw=None):
        exit_value = self.process.poll()
        if exit_value is not None:
            raise EOFError('[*] Triton has been terminated with exit code {}.'.format(exit_value))

        function = marshal.dumps(function.func_code)
        self.running = True
        self.connection.send({'action': 'run_to_condition', 'function': function, 'inclusive': include_this_address,
                              'commit': commit_next_instruction_to_hw})
        print '[>] Triton is running'
concrete.py 文件源码 项目:amphitrite 作者: cosine0 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def eval(self, function):
        function = marshal.dumps(function.func_code)
        self.connection.send({'action': 'eval', 'function': function})
        result = self.connection.recv()
        return result['return_value']


问题


面经


文章

微信
公众号

扫码关注公众号