summaryrefslogtreecommitdiff
path: root/demo/utils.py
blob: 03b1b3ab670c2d5c960f2aaf404e0b5f827eb257 (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import time 
import sys

PY_MAJOR_VERSION = sys.version_info[0]

if PY_MAJOR_VERSION > 2:
    NULL_CHAR = 0
else:
    NULL_CHAR = '\0'

def raise_error(error, message):
    # I have to exec() this code because the Python 2 syntax is invalid
    # under Python 3 and vice-versa.
    s = "raise "
    s += "error, message" if (PY_MAJOR_VERSION == 2) else "error(message)" 
        
    exec(s)


def say(s):
    """Prints a timestamped, self-identified message"""
    who = sys.argv[0]
    if who.endswith(".py"):
        who = who[:-3]
        
    s = "%s@%1.6f: %s" % (who, time.time(), s)
    print (s)


def write_to_memory(mapfile, s):
    """Writes the string s to the mapfile"""
    say("writing %s " % s)
    mapfile.seek(0)
    # I append a trailing NULL in case I'm communicating with a C program.
    s += '\0'
    if PY_MAJOR_VERSION > 2:
        s = s.encode()
    mapfile.write(s)


def read_from_memory(mapfile):
    """Reads a string from the mapfile and returns that string"""
    mapfile.seek(0)
    s = [ ]
    c = mapfile.read_byte()
    while c != NULL_CHAR:
        s.append(c)
        c = mapfile.read_byte()
            
    if PY_MAJOR_VERSION > 2:
        s = [chr(c) for c in s]
    s = ''.join(s)
    
    say("read %s" % s)
    
    return s


def read_params():
    """Reads the contents of params.txt and returns them as a dict"""
    params = { }
    
    f = open("params.txt")
    
    for line in f:
        line = line.strip()
        if line:
            if line.startswith('#'):
                pass # comment in input, ignore
            else:
                name, value = line.split('=')
                name = name.upper().strip()
            
                if name == "PERMISSIONS":
                    # Think octal, young man!
                    value = int(value, 8)
                elif "NAME" in name:
                    # This is a string; leave it alone.
                    pass
                else:
                    value = int(value)
                
                #print "name = %s, value = %d" % (name, value)
            
                params[name] = value

    f.close()
    
    return params