File: dumpcache.py

package info (click to toggle)
pypy 5.6.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 97,040 kB
  • ctags: 185,069
  • sloc: python: 1,147,862; ansic: 49,642; cpp: 5,245; asm: 5,169; makefile: 529; sh: 481; xml: 232; lisp: 45
file content (46 lines) | stat: -rw-r--r-- 1,705 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import os, sys
import ctypes


def dumpcache(referencefilename, filename, config):
    dirname = os.path.dirname(referencefilename)
    filename = os.path.join(dirname, filename)
    f = open(filename, 'w')
    print >> f, 'import ctypes'
    print >> f
    names = config.keys()
    names.sort()
    print >> f, '__all__ = %r' % (tuple(names),)
    print >> f
    for key in names:
        val = config[key]
        if isinstance(val, (int, long)):
            f.write("%s = %d\n" % (key, val))
        elif val is None:
            f.write("%s = None\n" % key)
        elif isinstance(val, ctypes.Structure.__class__):
            f.write("class %s(ctypes.Structure):\n" % key)
            f.write("    _fields_ = [\n")
            for k, v in val._fields_:
                f.write("        ('%s', %s),\n" % (k, ctypes_repr(v)))
            f.write("    ]\n")
        elif isinstance(val, (tuple, list)):
            for x in val:
                assert isinstance(x, (int, long, str)), \
                       "lists of integers or strings only"
            f.write("%s = %r\n" % (key, val))
        else:
            # a simple type, hopefully
            f.write("%s = %s\n" % (key, ctypes_repr(val)))
    f.close()
    print 'Wrote %s.' % (filename,)
    sys.stdout.flush()

def ctypes_repr(cls):
    # ctypes_configure does not support nested structs so far
    # so let's ignore it
    if isinstance(cls, ctypes._SimpleCData.__class__):
        return "ctypes." + cls.__name__
    if hasattr(cls, '_length_') and hasattr(cls, '_type_'):  # assume an array
        return '%s*%d' % (ctypes_repr(cls._type_), cls._length_)
    raise NotImplementedError("saving of object with type %r" % type(cls))