示例#1
0
def test_shift_left():
    asm_path = join(dirname(dirname(__file__)), 'lib', 'binary', 'shift.asm')
    asm = template.format(arg='{arg}', call='binary_shift_left', path=asm_path)

    assert VirtualMachine().run(asm.format(arg=10)) == '20'
    assert VirtualMachine().run(asm.format(arg=1)) == '2'
    assert VirtualMachine().run(asm.format(arg=0)) == '0'
示例#2
0
    def __init__(self):
        
        # Windows does not have GNU readline, and has different environment variables
        if osname == 'nt':
            username = environ["USERNAME"]
        else:
            import readline
            import atexit
            username = environ["USER"]
            
            # Uses the readline library to gain tab completion, matching
            # parenthesis, and automatic history
            readline.set_completer(self.complete)
            readline.parse_and_bind('tab: complete')
            readline.parse_and_bind('set blink-matching-paren on')
    
            self.histfile = join(expanduser("~"), ".pylisp_history")
            try:
                readline.read_history_file(self.histfile)
            except FileNotFoundError:
                open(self.histfile, 'a').close()
    
            self.completion_candidates = []
    
            atexit.register(readline.write_history_file, self.histfile)
            
        # Initialises using the user's username as the prompt
        self.prompt = username + "> "

        self.intro = "Welcome to the PyLisp interpreter"

        self.vm = VirtualMachine({})
        self.load_std()
        self.registers = None
示例#3
0
def test_divide():
    asm_path = join(dirname(dirname(__file__)), 'lib', 'math', 'divide.asm')
    asm = template.format(arg0='{arg0}', arg1='{arg1}', call='math_divide',
                          path=asm_path)

    assert VirtualMachine().run(asm.format(arg0=10, arg1=2)) == '5'
    assert VirtualMachine().run(asm.format(arg0=5, arg1=7)) == '0'
    assert VirtualMachine().run(asm.format(arg0=25, arg1=25)) == '1'
    assert VirtualMachine().run(asm.format(arg0=10, arg1=1)) == '10'
示例#4
0
def test_multiply():
    asm_path = join(dirname(dirname(__file__)), 'lib', 'math', 'multiply.asm')
    asm = template.format(arg0='{arg0}', arg1='{arg1}', call='math_multiply',
                          path=asm_path)
    # asm += open(asm_path).read()

    print(asm)

    assert VirtualMachine().run(asm.format(arg0=10, arg1=2)) == '20'
    assert VirtualMachine().run(asm.format(arg0=5, arg1=7)) == '35'
    assert VirtualMachine().run(asm.format(arg0=25, arg1=10)) == '250'
    assert VirtualMachine().run(asm.format(arg0=10, arg1=25)) == '250'
示例#5
0
    def getVirtualMachineByName(self, name, folder=None):
        """Return VM object using PyVmomi"""

        recursive = True

        if folder is None or folder == '/':

            content = self._vmh.content
            container = content.rootFolder
            viewType = [vim.VirtualMachine]
            vmView = content.viewManager.CreateContainerView(
                container, viewType, recursive)
            vms = vmView.view
            for vm in vms:
                if vm.name == name:
                    return VirtualMachine(vm)
            raise Exception(
                'Impossibile trovare una VM con nome {}\n'.format(name))

        vmList = self.getVirtualMachineList(folder, recursive)

        for vm in vmList:
            if vm.name == name:
                return vm

        raise Exception(
            'Impossibile trovare una VM con nome {}\n'.format(name))
示例#6
0
    def getVirtualMachineList(self,
                              folder=None,
                              recursive=False,
                              template=False):

        if (type(folder) == str):
            container = self.getFolderByName(folder)
        elif (type(folder) == vim.Folder):
            container = folder
        elif folder is None:
            container = self.getFolderByName('/')

        containers = [container]

        while containers:

            container = containers.pop()

            for child in container.childEntity:

                if type(child) == vim.VirtualMachine:

                    if template or not self._isVmTemplate(child):
                        yield VirtualMachine(child)

                elif type(child) == vim.Folder and recursive == True:
                    containers.append(child)

        raise StopIteration
示例#7
0
文件: vcenter.py 项目: DarrenTeng/TYZ
    def get_all_vms(self):
        all_vms = []

        vim_type = [vim.VirtualMachine]
        objects = self.__get_all_objects_by_type(vim_type)
        for obj in objects:
            if not obj.config.template:
                all_vms.append(VirtualMachine(obj))

        return all_vms
示例#8
0
    def getVirtualMachineByMoId(self, moid):
        """Lookup a vm from a given moId string (like "vm-123" """

        vm_obj = vim.VirtualMachine(moid)

        try:
            vm_obj._stub = self._vmh._stub
        except Exception:
            raise Exception(
                'Impossibile trovare una VM con moid {}'.format(moid))

        return VirtualMachine(vm_obj)
示例#9
0
文件: vcenter.py 项目: DarrenTeng/TYZ
    def get_all_templates(self):
        global all_templates
        if (len(all_templates) != 0):
            return all_templates
        vim_type = [vim.VirtualMachine]
        objects = self.__get_all_objects_by_type(vim_type)
        for obj in objects:
            try:
                if obj.config.template:
                    all_templates.append(VirtualMachine(obj))
            except:
                pass

        return all_templates
示例#10
0
    def getVirtualMachineIpAddress(self, ip):
        """Return VM object using PyVmomi"""

        searchIndex = self._vmh.RetrieveContent().searchIndex
        _vms = searchIndex.FindAllByIp(ip=ip, vmSearch=True)
        vms = []
        oid = []

        for vm in _vms:
            if vm._moId not in oid:
                oid.append(vm._moId)
                vms.append(VirtualMachine(vm))

        return vms
示例#11
0
文件: vcenter.py 项目: DarrenTeng/TYZ
    def get_vm_by_name(self, name):
        vim_type = [vim.VirtualMachine]
        objects = self.__get_all_objects_by_type(vim_type)
        all_vms = []

        for obj in objects:
            try:
                if not obj.config.template:
                    all_vms.append(VirtualMachine(obj))
            except:
                pass

        for vm in all_vms:
            if vm.name == name:
                return vm

        return -1
示例#12
0
文件: main.py 项目: rslabbert/PyLisp
def main():
    """
    The main function called when the program is run. Will either start the interpreter or run a file if a filename is provided
    """
    if len(sys.argv) == 1:
        from interpreter import Interpreter

        # Main loop which prompts user for input and print the response of the input handed to the rep function
        interpreter = Interpreter()
        interpreter.load_std()
        interpreter.cmdloop()
    else:
        from fileparser import FileParser
        from virtualmachine import VirtualMachine

        parser = FileParser(sys.argv[1], VirtualMachine({}))
        parser.load_std()
        parser.run()
示例#13
0
文件: vcenter.py 项目: DarrenTeng/TYZ
 def get_vm_by_uuid(self, uuid):
     vm = VirtualMachine(self.__get_obj_by_uuid(uuid))
     return vm
示例#14
0
 def add_vm(self, ip, vmid, alias):
     self.vms.append(VirtualMachine(ip, vmid, alias))
示例#15
0
def _match(pattern, iterable):
    assert isinstance(pattern, Pattern)
    code = pattern.compile()
    vm = VirtualMachine(code)
    m = Match()
    # Start VM
    vm.do_epsilon_transitions()
    m.state = vm.accepting_state(None)
    vm.cutoff()
    for x in iterable:
        if not vm.is_alive():
            break
        vm.feed(x)
        vm.do_epsilon_transitions()
        m.state = vm.accepting_state(m.state)
        vm.cutoff()
    if m.state == None:
        return None
    return m
示例#16
0
def finditer_alt(pattern, iterable):
    """
    An experimental implementation of finditer.
    The idea here is to make an implementation that is able to work with any
    iterator, not necessariry the indexable ones.
    This implies (among other things) that each element is feeded only once and
    then discarded.
    """
    assert isinstance(pattern, Pattern)
    pattern = Star(Star(Any(), greedy=False) + Group(pattern, None))
    code = pattern.compile()
    vm = VirtualMachine(code)
    m = Match()
    new = Match()
    # Start VM
    vm.do_epsilon_transitions()
    vm.cutoff()
    for x in iterable:
        if not vm.is_alive():
            break
        vm.feed(x)
        vm.do_epsilon_transitions()
        new.state = vm.accepting_state(None)
        if new.state != None:
            if m.state == None:
                m.state = new.state
            elif m.start() == new.start() and m.end() < new.end():
                m.state = new.state
            elif m.start() != new.start():
                yield m
                m = new
                new = Match()
        vm.cutoff()
    if m.state != None:
        yield m
示例#17
0
class Interpreter():
    """
    A read eval print loop interactive interpreter. Takes input from the user and displays the resultant output on the next line
    """

    def __init__(self):
        
        # Windows does not have GNU readline, and has different environment variables
        if osname == 'nt':
            username = environ["USERNAME"]
        else:
            import readline
            import atexit
            username = environ["USER"]
            
            # Uses the readline library to gain tab completion, matching
            # parenthesis, and automatic history
            readline.set_completer(self.complete)
            readline.parse_and_bind('tab: complete')
            readline.parse_and_bind('set blink-matching-paren on')
    
            self.histfile = join(expanduser("~"), ".pylisp_history")
            try:
                readline.read_history_file(self.histfile)
            except FileNotFoundError:
                open(self.histfile, 'a').close()
    
            self.completion_candidates = []
    
            atexit.register(readline.write_history_file, self.histfile)
            
        # Initialises using the user's username as the prompt
        self.prompt = username + "> "

        self.intro = "Welcome to the PyLisp interpreter"

        self.vm = VirtualMachine({})
        self.load_std()
        self.registers = None
        
    def load_std(self):
        """
        Adds the core libraries to the environment
        """
        for i in env.standard_env:
            libs = env.include_lib(i)
            for lib in libs:
                if lib[0] == "py":
                    self.vm.env.update(lib[1])
                elif lib[0] == "pyl":
                    file_parse = FileParser(lib[1], self.vm)
                    file_parse.run()

    def complete(self, text, state):
        """
        The completer function. Works by finding all the symbols in the environment and in the core keywords and checking if they start with the provided text
        """
        if state == 0:
            self.completion_candidates = []

            tmp = []
            tmp.extend(self.repl_env.keys())
            tmp.extend(self.vm.core_keywords.keys())

            for i in tmp:
                if i.startswith(text):
                    self.completion_candidates.append(i)

        if state < len(self.completion_candidates):
            result = self.completion_candidates[state]
        else:
            result = None

        return result

    def precmd(self, line):
        """
        Executed on the input before the line is evaluated. Used to ensure that if the opening brackets do not match the closing brackets, the prompt is just extended
        """
        ret = line
        prompt_indent = len(self.prompt) - len("...")
        while ret.count("(") > ret.count(")"):
            indent = (ret.count("(") - ret.count(")")) * 2
            ret += " " + \
                input("\r" + " " * prompt_indent + "..." + indent * " ")

        return ret

    def cmdloop(self):
        """
        The main loop. Gets the input, sends it to precmd, then runs it. If it encounters a pylisp error, prints the error and cleans up.
        If it enconters an EOF i.e. Ctrl-D it closes gracefully
        """
        print(self.intro)
        while True:
            self.registers = self.vm.get_registers()
            try:
                inp = input(self.prompt)
                inp = self.precmd(inp)

                parser = Parser()
                print(self.vm.evaluate(parser.parse_buffer(inp)))

            except PylispError as e:
                print(e)
                self.vm.set_registers(self.registers)
            except (KeyboardInterrupt, EOFError):
                return
示例#18
0
def vm():
    return VirtualMachine()
示例#19
0
文件: sota.py 项目: sota/trials
                    '--version',
                    action='version',
                    version=VERSION,
                    help='print the version and exit')
    ap.add_argument('-v',
                    '--verbose',
                    action='store_true',
                    help='print verbosely')
    ap.add_argument('source', default=None, nargs='?', help='text | file')

    ns = ap.parse_args()
    print ns

    lexer = Lexer(PATTERNS, ns.verbose)
    parser = Parser(ns.verbose)
    vm = VirtualMachine()

    if not ns.source:
        exitcode = repl(lexer, parser)

    if os.path.isfile(ns.source):
        source = open(ns.source).read()
    else:
        source = '(print %s)' % ns.source

    tokens = lexer.Scan(source)
    opcodes = parser.Parse(tokens)
    exitcode = vm.Execute(opcodes)

    sys.exit(exitcode)