1import time 2import sys 3 4PY_MAJOR_VERSION = sys.version_info[0] 5 6if PY_MAJOR_VERSION > 2: 7 NULL_CHAR = 0 8else: 9 NULL_CHAR = '\0' 10 11 12def raise_error(error, message): 13 # I have to exec() this code because the Python 2 syntax is invalid 14 # under Python 3 and vice-versa. 15 s = "raise " 16 s += "error, message" if (PY_MAJOR_VERSION == 2) else "error(message)" 17 18 exec(s) 19 20 21def say(s): 22 """Prints a timestamped, self-identified message""" 23 who = sys.argv[0] 24 if who.endswith(".py"): 25 who = who[:-3] 26 27 s = "%s@%1.6f: %s" % (who, time.time(), s) 28 print(s) 29 30 31def write_to_memory(mapfile, s): 32 """Writes the string s to the mapfile""" 33 say("writing %s " % s) 34 mapfile.seek(0) 35 # I append a trailing NULL in case I'm communicating with a C program. 36 s += '\0' 37 if PY_MAJOR_VERSION > 2: 38 s = s.encode() 39 mapfile.write(s) 40 41 42def read_from_memory(mapfile): 43 """Reads a string from the mapfile and returns that string""" 44 mapfile.seek(0) 45 s = [] 46 c = mapfile.read_byte() 47 while c != NULL_CHAR: 48 s.append(c) 49 c = mapfile.read_byte() 50 51 if PY_MAJOR_VERSION > 2: 52 s = [chr(c) for c in s] 53 s = ''.join(s) 54 55 say("read %s" % s) 56 57 return s 58 59 60def read_params(): 61 """Reads the contents of params.txt and returns them as a dict""" 62 params = {} 63 64 f = open("params.txt") 65 66 for line in f: 67 line = line.strip() 68 if line: 69 if line.startswith('#'): 70 pass # comment in input, ignore 71 else: 72 name, value = line.split('=') 73 name = name.upper().strip() 74 75 if name == "PERMISSIONS": 76 # Think octal, young man! 77 value = int(value, 8) 78 elif "NAME" in name: 79 # This is a string; leave it alone. 80 pass 81 else: 82 value = int(value) 83 84 # print "name = %s, value = %d" % (name, value) 85 86 params[name] = value 87 88 f.close() 89 90 return params 91