本文整理汇总了Python中memory.Memory.read方法的典型用法代码示例。如果您正苦于以下问题:Python Memory.read方法的具体用法?Python Memory.read怎么用?Python Memory.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类memory.Memory
的用法示例。
在下文中一共展示了Memory.read方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
def read(self, **kwargs):
"""
Memory.read returns a list for all bitfields, so just put those
values into single values.
"""
memdata = Memory.read(self, **kwargs)
results = memdata['data']
timestamp = memdata['timestamp']
for k, v in results.iteritems():
results[k] = v[0]
self.last_values = results
return {'data': results, 'timestamp': timestamp}
示例2: Chip8
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
class Chip8(object):
ENTRY_POINT = 0x200
REG_COUNT = 16
KEY_COUNT = 16
def __init__(self):
self.registers = bytearray(self.REG_COUNT)
self.index_register = 0
self.program_counter = self.ENTRY_POINT
self.memory = Memory()
self.screen = Screen()
self.keyboard = bytearray(self.KEY_COUNT)
self.stack = []
self.delay_timer = 0
self.sound_timer = 0
self.INSTRUCTION_SET = {
0x00E0: self.op_00E0,
0x00EE: self.op_00EE,
0x1 : self.op_1NNN,
0x2 : self.op_2NNN,
0x3 : self.op_3XNN,
0x4 : self.op_4XNN,
0x5 : self.op_5XY0,
0x6 : self.op_6XNN,
0x7 : self.op_7XNN,
0x8000: self.op_8XY0,
0x8001: self.op_8XY1,
0x8002: self.op_8XY2,
0x8003: self.op_8XY3,
0x8004: self.op_8XY4,
0x8005: self.op_8XY5,
0x8006: self.op_8XY6,
0x8007: self.op_8XY7,
0x800E: self.op_8XYE,
0x9000: self.op_9XY0,
0xA : self.op_ANNN,
0xB : self.op_BNNN,
0xC : self.op_CXNN,
0xD : self.op_DXYN,
0xE09E: self.op_EX9E,
0xE0A1: self.op_EXA1,
0xF007: self.op_FX07,
0xF00A: self.op_FX0A,
0xF015: self.op_FX15,
0xF018: self.op_FX18,
0xF01E: self.op_FX1E,
0xF029: self.op_FX29,
0xF033: self.op_FX33,
0xF055: self.op_F055,
0xF065: self.op_FX65,
}
def decode(self, op):
if op in [0x00E0, 0x00EE]: # special case
return (op, tuple())
instruction = I(op)
if instruction in [0x0, 0x1, 0x2, 0xA, 0xB]:
args = (NNN(op),)
elif instruction in [0x3, 0x4, 0x6, 0x7, 0xC]:
args = X(op), NN(op)
elif instruction == 0x5:
args = X(op), Y(op)
elif instruction == 0xD:
args = X(op), Y(op), N(op)
elif 0x8000 <= instruction <= 0x9000:
args = X(op), Y(op)
elif instruction >= 0xE:
args = (X(op),)
return instruction, args
def execute(self, instruction, args):
if instruction not in self.INSTRUCTION_SET:
raise NotImplementedError('{:04x} - {}'.format(instruction, args))
self.INSTRUCTION_SET.get(instruction)(*args)
def fetch(self):
return self.memory.read_word(self.program_counter)
def cycle(self):
word = self.fetch()
instruction, args = self.decode(word)
self.execute(instruction, args)
if self.delay_timer > 0:
self.delay_timer -= 1
if self.sound_timer > 0:
if self.sound_timer == 1:
#.........这里部分代码省略.........
示例3: __init__
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
class Controller:
def __init__(self):
"""Model of a standard contoller unit demonstrating the Texas 4-step (fetch,decode,execute,store) with methods for each."""
self.R1 = 0 # General purpose register to store final result.
self.R2 = 0 # General purpose register to store file length.
self.R3 = "" # Storage register to store mnemonic from memory.
self.IR = 0 # Instruction register
self.PC = 0 # Program counter/accumulator
self.running = False # Machine state
self.clock = time.time() # Start system clock
self.ALU = ALU() # Arithmetic-logic units
self.MEM = Memory() # System memory
def loader(self, cfile):
"""Load file data into memory prior 4-step and store it into gp register R2."""
io("Loading " + cfile + "...")
self.R2 = self.MEM.loader(cfile)
io("Processed: " + str(self.R2) + " lines.")
io("Machine is running...")
self.running = True
def fetch(self):
"""Fetch next instruction stored in memory using PC address and store it into storage register R3."""
self.R3 = self.MEM.read(self.PC)
io("|FETCH|--> address(" + str(self.PC) + ")")
io(">read(" + str(self.PC) + "->" + self.R3 + ")")
def decode(self):
"""Decode data fetched. Determine if valid value or instruction, bump accumulator, and store in inst register IR."""
self.PC += 1
try:
self.IR = int(self.R3)
self.R3 = "push"
io("\t|DECODE|--> decoding(" + str(self.IR) + ")...")
io("\t>found operand(" + str(self.IR) + ")")
io("\t>valid instruction")
except ValueError:
self.IR = self.R3
io("\t|DECODE|--> decoding(" + self.IR + ")...")
io("\t>found operator(" + self.IR + ")")
io("\t>valid instruction")
def execute(self):
"""Execute instruction fetched from memory and operate/manage stack memory."""
op = self.R3
if op == "push":
io("\t\t|EXECUTE|--> " + op)
io("\t\t>pushed(" + str(self.IR) + ")")
self.MEM.push(self.IR)
else:
op1, op2 = self.MEM.pop()
io("\t\t|EXECUTE|--> " + op + "(" + str(op1) + "," + str(op2) + ")")
io("\t\t>pop <-(" + str(op1) + ")")
io("\t\t>pop <-(" + str(op2) + ")")
self.R1 = self.ALU.operate(op, op1, op2)
io("\t\t>push ->(" + str(self.R1) + ")")
self.MEM.push(self.R1)
def store(self):
"""Store resulting data, output value that is stored in register."""
io("\t\t\t|STORE|--> storing(" + str(self.R1) + ")")
def run(self):
"""Start steppin. Begin the Texas 4-step, calculate/display the total processing time, and display final result."""
while self.running and self.PC < self.R2:
io("=" * 62)
self.fetch()
self.decode()
self.execute()
self.store()
io(
"=" * 62
+ "\nResult:\t"
+ str(self.R1)
+ "\nTime :\t"
+ str(round(time.time() - self.clock, 4))
+ " s\n"
+ "=" * 62
)
示例4: __init__
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
class Draugr :
def __init__(self, memory, mmap) :
self.m = Memory(memory, "r", mmap)
self.b = None
# pgd = unpack("<L", self.m.read(lpid[mypid].mm + 36, 4))[0]
# print hex(lpid[mypid].mm), hex(pgd)
# print hex(self.m.pgd_to_pte(0xde101000)) #pgd))
# print hex(self.m.pgd_to_pte(pgd))
def page(self, pid, addr, size=4096) :
if self.b == None :
self.b = BuildTaskStruct(self.m)
self.b.find_offsets()
lpid = DraugrLinkedPid(self.m, self.b).runHash()
print lpid[pid]
pgd = unpack("<L", self.m.read(lpid[pid].mm + 36, 4))[0]
print hex(pgd)
page = self.m.page(pgd, addr)
print "PAGE @ 0x%lx" % page
print self.m.dump(page, size, 'd')
def lprocesses(self) :
if self.b == None :
self.b = BuildTaskStruct(self.m)
self.b.find_offsets()
lpid = DraugrLinkedPid(self.m, self.b)
for i in lpid.run() :
print i
def bprocesses(self, start=0xc0000000) :
if self.b == None :
self.b = BuildTaskStruct(self.m)
self.b.find_offsets()
l = []
upid = DraugrUnknownPid(self.m, self.b, start)
for i in upid.run() :
l.append(i)
print
for x in l :
print x
def symbol(self, name) :
if name[0] == 'd' :
addr = self.m.symbol(name[2:])
elif name[0] == 'x' :
addr = self.m.symbolXML(name[2:])
elif name[0] == 's' :
addr = self.m.syscall(int(name[2:]))
else :
raise("Ooops")
print "%s @ 0x%lx" % (name[2:], addr)
def disasm(self, addr, size) :
for i in self.m.disasm(addr, size) :
print "0x%08x (%02x) %-20s %s" % (i.offset, i.size, i.instructionHex, str(i.mnemonic) + " " + str(i.operands))
def dump(self, addr, size) :
print self.m.dump(addr, size, 'h')
示例5: __init__
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
class X86Machine:
registernames = { X86_REG_RAX : "RAX",
X86_REG_RCX : "RCX",
X86_REG_RDX : "RDX",
X86_REG_RBX : "RBX",
X86_REG_RSP : "RSP",
X86_REG_RBP : "RBP",
X86_REG_RSI : "RSI",
X86_REG_RDI : "RDI",
X86_REG_R8 : "R8",
X86_REG_R9 : "R9",
X86_REG_R10 : "R10",
X86_REG_R11 : "R11",
X86_REG_R12 : "R12",
X86_REG_R13 : "R13",
X86_REG_R14 : "R14",
X86_REG_R15 : "R15"}
regs_32 = {X86_REG_EAX : X86_REG_RAX,
X86_REG_ECX : X86_REG_RCX,
X86_REG_EDX : X86_REG_RDX,
X86_REG_EBX : X86_REG_RBX,
X86_REG_ESP : X86_REG_RSP,
X86_REG_EBP : X86_REG_RBP,
X86_REG_ESI : X86_REG_RSI,
X86_REG_EDI : X86_REG_RDI,
X86_REG_R8D : X86_REG_R8,
X86_REG_R9D : X86_REG_R9,
X86_REG_R10D : X86_REG_R10,
X86_REG_R11D : X86_REG_R11,
X86_REG_R12D : X86_REG_R12,
X86_REG_R13D : X86_REG_R13,
X86_REG_R14D : X86_REG_R14,
X86_REG_R15D : X86_REG_R15}
regs_8 = {X86_REG_AL : X86_REG_RAX,
X86_REG_CL : X86_REG_RCX,
X86_REG_DL : X86_REG_RDX,
X86_REG_BL : X86_REG_RBX,
X86_REG_R8B : X86_REG_R8,
X86_REG_R9B : X86_REG_R9,
X86_REG_R10B : X86_REG_R10,
X86_REG_R11B : X86_REG_R11,
X86_REG_R12B : X86_REG_R12,
X86_REG_R13B : X86_REG_R13,
X86_REG_R14B : X86_REG_R14,
X86_REG_R15B : X86_REG_R15}
initsp = 0xffff0000
def __init__(self):
self.instcount = 0
self.regs = {}
self.xmmregs = []
self.mem = Memory(7)
self.carry = NFree('initialcarry')
self.uniq = 1
self.breakpoints = {}
for i in self.registernames:
self.regs[i] = NFree("init_"+self.registernames[i])
self.regs[X86_REG_RSP] = NValue(self.initsp) # We use a special initial stack value
for i in range(32):
self.xmmregs.append(NFree("initxmm_"+str(i),128))
def breakpoint(self,addr):
self.breakpoints[addr] = True
def print_state(self):
for x in self.registernames:
val = self.readreg(x)
if(isinstance(val,NValue)):
print self.registernames[x], val.as_long()
def operandsize(self,i, idx):
op = i.operands[idx]
if(op.type == X86_OP_IMM or op.type == X86_OP_MEM):
return i.op_size * 8
elif op.type == X86_OP_REG:
if op.reg in self.registernames:
return 64
elif(op.reg >= X86_REG_XMM0 and op.reg <= X86_REG_XMM31):
return 128
elif op.reg in self.regs_32:
return 32
elif op.reg in self.regs_8:
return 8
else:
raise MiscError()
def solve_memoperand(self,op):
value = NValue(op.disp)
if(op.index != 0):
if(op.scale == 1):
value = value + self.regs[op.index]
else:
value = value + NValue(op.scale,64) * self.regs[op.index]
if(op.base != 0):
if(op.base == X86_REG_RIP):
value = value + self.ip
else:
value = value + self.regs[op.base]
return value
#.........这里部分代码省略.........
示例6: Memory
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
from memory import Memory
m = Memory()
r = m.alloc("xyz", 14)
print r
print m
r = m.alloc("abc", 12)
print r
print m
r = m.read("xyz", 4, 5)
print r
print m
r = m.deleteFile("xyz")
print r
print m
r = m.deleteFile("abc")
print r
print m
示例7: set
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
class Server:
backlog = 5
# this set will serve as a filesystem index
files = set()
def __init__(self, port):
# creates server object
global blocksize, n_blocks
path = ".storage"
try:
os.makedirs(path)
except OSError as exception:
shutil.rmtree(path)
os.makedirs(path)
host = ""
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind((host, port))
self.port = port
self.memory = Memory(n_blocks, blocksize)
print "Block size is", blocksize
print "Number of blocks is", n_blocks
def process_line(self, client):
# recv's until \n
recieved = ""
while True:
cur = client.recv(1)
if cur == "\n":
break
elif not cur:
return cur
else:
recieved += cur
return recieved
def listen(self):
# Handles initial client connections and thread creation
self.s.listen(self.backlog)
print "Listening on port", self.port
while True:
client, address = self.s.accept()
print "Received incoming connection from", address[0]
cmd = self.process_line(client)
thread = threading.Thread(target=self.handler, args=(cmd, client))
thread.start()
# the following functions implement the server functionality requested
def store(self, client, args):
thread = str(threading.current_thread().ident)
if len(args) != 3:
client.send("ERROR: INVALID COMMAND.\n")
print "[thread", thread + "] Sent: ERROR: INVALID COMMAND."
return
args[2] = int(args[2])
if args[1] in self.files:
client.send("ERROR: FILE EXISTS.\n")
print "[thread", thread + "] Sent: ERROR: FILE EXISTS."
data = client.recv(args[2]) # can we assume data will be sent regardless of error?
return
response = self.memory.alloc(args[1], args[2])
if not response[0]:
client.send("ERROR: INSUFFICIENT DISK SPACE.\n")
print "[thread", thread + "] Sent: ERROR: INSUFFICIENT DISK SPACE."
data = client.recv(args[2]) # can we assume data will be sent regardless of error?
return
# actually do the storing stuff
data = client.recv(args[2])
f = open(".storage/" + args[1], "w")
f.write(data)
self.files.add(args[1])
print "[thread", thread + "] Stored file '%s' (%s bytes; %s blocks; %s" % response, (
"cluster" if response[3] == 1 else "cluster"
) + ")"
print "[thread", thread + "] Simulated Clustered Disk Space Allocation:"
print self.memory
client.send("ACK\n")
print "[thread", thread + "] Sent: ACK"
def read(self, client, args):
thread = str(threading.current_thread().ident)
if len(args) != 4:
client.send("ERROR: INVALID COMMAND.\n")
print "[thread", thread + "] Sent: ERROR: INVALID COMMAND."
return
if args[1] not in self.files:
client.send("ERROR: NO SUCH FILE.\n")
print "[thread", thread + "] Sent: ERROR: NO SUCH FILE."
return
args[2] = int(args[2])
args[3] = int(args[3])
data = open(".storage/" + args[1], "r").read()
if args[2] + args[3] > len(data) or args[2] < 0 or args[3] < 0:
client.send("ERROR: INVALID BYTE RANGE.\n")
print "[thread", thread + "] Sent: ERROR: INVALID BYTE RANGE."
return
# TODO: (1) Memory dump / print output
result = "ACK " + str(args[3]) + "\n" + data[args[2] : args[2] + args[3]]
print "[thread", thread + "] Sent: ACK", args[3]
client.send(result)
response = self.memory.read(args[1], args[2], args[3])
#.........这里部分代码省略.........
示例8: read_user_input
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
from memory import Memory
def read_user_input(prompt='> ', end_program='end_program'):
line_list = []
line = input(prompt).strip()
while line != '':
if line == end_program:
return end_program
line_list.append(line)
line = input(prompt).strip()
return ' '.join(line_list)
def converse(converse_memory, seed_index='', end_program='end_program'):
prev_index = seed_index.strip()
while True:
utterance, prev_index = converse_memory.construct(prev_index)
print(utterance)
user_input = read_user_input(end_program=end_program)
if user_input == end_program:
break
prev_index = converse_memory.remember(user_input, prev_index)
return prev_index
if __name__ == "__main__":
converse_memory = Memory()
converse_memory.read('', '../data/converse_preload.txt')
prev_index = converse(converse_memory, '')
converse_memory.save('../data/converse_memory.pkl')
示例9: __init__
# 需要导入模块: from memory import Memory [as 别名]
# 或者: from memory.Memory import read [as 别名]
class Cpu:
def __init__(self, verbose, scale):
#
self._verbose = verbose
# CPU properties
# 16 general purpose 8-bit registers
self._reg = array.array('B', [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
# 16-bit register
self._I = array.array('H', [0])
# Timers delay = 0 / sound = 1
self._timer = array.array('B', [0,0])
# Stack
self._stack = array.array('H', [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
# Program Counter
self._PC = array.array('H', [0x0200])
# Memory
self.memory = Memory()
# Video
self.video = Video(verbose, scale)
# Key states
self._keystate = array.array('B', [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
# private properties
self.__ips = 60
self.clock = pygame.time.Clock()
def execute(self):
word = (self.memory.read(self._PC[0]) << 8) | (self.memory.read(self._PC[0] + 1))
n1 = (word >> 12) & 0x0f
n2 = (word >> 8) & 0x0f
n3 = (word >> 4) & 0x0f
n4 = word & 0x0f
if self._verbose: print "Opcode: %x" % (word)
self._PC[0] = self._PC[0] + 2
if n1 == 0x0:
if n2 == 0:
if n3 == 0xc:
print "00CN Scroll down %i lines (***)" % (n4)
sys.exit(1)
elif n3 == 0xf and n4 == 0xb:
print "00FB Scroll 4 pixels right (***)"
sys.exit(1)
elif n3 == 0xf and n4 == 0xc:
print "00FC Scroll 4 pixels left (***)"
sys.exit(1)
elif n3 == 0xf and n4 == 0xd: # 00FD Quit the emulator (***)
sys.exit(1)
elif n3 == 0xf and n4 == 0xe: # 00FE Set CHIP-8 graphic mode (***)
print "TODO: not implemented"
sys.exit(1)
elif n3 == 0xf and n4 == 0xf: # 00FF Set SCHIP graphic mode (***)
print "TODO: not implemented"
sys.exit(1)
elif n3 == 0xe and n4 == 0x0: # 00E0 Erase the screen
self.video.erase()
elif n3 == 0xe and n4 == 0xe: # 00EE Return from a CHIP-8 sub-routine
self._PC[0] = self._stack.pop()
else:
print "Error %2x%2x%2x%2x" % (n1,n2,n3,n4)
sys.exit(1)
else: # 0NNN Call 1802 machine code program at NNN (not implemented)
print "0NNN Call 1802 machine code program at NNN (not implemented)"
sys.exit(1)
elif n1 == 0x1: # 1NNN Jump to NNN
self._PC[0] = word & 0x0fff
elif n1 == 0x2: # 2NNN Call CHIP-8 sub-routine at NNN (16 successive calls max)
self._stack.append(self._PC[0])
self._PC[0] = word & 0x0fff
elif n1 == 0x3: # 3XKK Skip next instruction if VX == KK
if self._reg[n2] == (word & 0x00ff):
self._PC[0] = self._PC[0] + 2
elif n1 == 0x4: # 4XKK Skip next instruction if VX != KK
if self._reg[n2] != (word & 0x00ff):
self._PC[0] = self._PC[0] + 2
elif n1 == 0x5 and n4 == 0x0: # 5XY0 Skip next instruction if VX == VY
if self._reg[n2] == self._reg[n3]:
self._PC[0] = self._PC[0] + 2
elif n1 == 0x6: # 6XKK VX = KK
self._reg[n2] = word & 0x00ff
elif n1 == 0x7: # 7XKK VX = VX + KK
self._reg[n2] = (self._reg[n2] + (word & 0x00ff)) & 0xff
elif n1 == 0x8:
if n4 == 0x0: # 8XY0 VX = VY
self._reg[n2] = self._reg[n3]
elif n4 == 0x1: # 8XY1 VX = VX OR VY
self._reg[n2] = self._reg[n2] | self._reg[n3]
elif n4 == 0x2: # 8XY2 VX = VX AND VY
self._reg[n2] = self._reg[n2] & self._reg[n3]
elif n4 == 0x3: #8XY3 VX = VX XOR VY (*)
self._reg[n2] = self._reg[n2] ^ self._reg[n3]
elif n4 == 0x4: # 8XY4 VX = VX + VY, VF = carry
if (self._reg[n2] + self._reg[n3]) > 0xff:
self._reg[0xf] = 1
else:
self._reg[0xf] = 0
self._reg[n2] = (self._reg[n2] + self._reg[n3]) & 0xff
elif n4 == 0x5: # 8XY5 VX = VX - VY, VF = not borrow (**)
if self._reg[n2] < self._reg[n3]:
self._reg[0xf] = 0
#.........这里部分代码省略.........