本文整理汇总了Python中interpreter.Interpreter.interpret方法的典型用法代码示例。如果您正苦于以下问题:Python Interpreter.interpret方法的具体用法?Python Interpreter.interpret怎么用?Python Interpreter.interpret使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类interpreter.Interpreter
的用法示例。
在下文中一共展示了Interpreter.interpret方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compile_pascal
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
def compile_pascal(source, dest, is_debug = False, is_interpret = False, out_stream = sys.stdout, output_tokens = False, output_bytecodes = False, lib = ['.'], in_stream = sys.stdin):
'''
DID YOU KNOW that compile() is a built in function?
'''
set_debug(is_debug)
debug("Compiling %s into %s" % (source, dest))
scanner = Scanner(source)
tokens = scanner.scan()
if output_tokens:
write(tokens, source + "_tokenized")
debug('scanning complete')
parser = Parser(tokens, source, lib = lib)
bytecodes, success = parser.parse()
if output_bytecodes:
if is_debug:
write(prettify(bytecodes), source + "_unassembled")
else:
write(bytecodes, source + "_unassembled")
if not success:
print 'Parsing error'
return
debug('parsing complete')
assembler = Assembler(bytecodes)
assembled = assembler.assemble()
if is_debug:
write(prettify(assembled), dest + '_debug')
write(assembled, dest)
debug('assembly complete.' )
if is_interpret:
interp = Interpreter(out_stream, in_stream, code = assembled)
interp.interpret()
else:
debug('run program now with `python interpreter.py %s`' % dest)
示例2: run
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
def run(self):
plugin_loader = PluginLoader()
plugin_directory = PluginDirectory()
commands = plugin_loader.load(plugin_directory)
interpreter = Interpreter(commands)
while True:
print interpreter.interpret(raw_input())
示例3: test
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
def test(text):
print
print text
lexer = Lexer()
tokens = lexer.tokenize(text)
print tokens
parser = Parser()
ast = parser.parse(tokens)
print ast
print fmt(ast)
interpreter = Interpreter()
interpreter.interpret(ast, None)
示例4: run
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
class Application:
input_source = KeyboardInput
def run(self):
plugin_loader = PluginLoader()
plugin_directory = PluginDirectory()
commands = plugin_loader.load(plugin_directory)
self.interpreter = Interpreter(commands)
poller = Poller(self.input_source, self.input_evaluator)
poller.poll()
def input_evaluator(self, user_input):
if user_input is None:
user_input = self.input()
result = self.interpreter.interpret(user_input)
if result is not None:
if isinstance(result, str):
lines = result.split('\n')
if len(lines) > 1:
for line in lines:
self.output(line)
else:
self.output(result)
else:
self.output(result)
def output(self, result):
print result
示例5: run
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
def run(fname):
with open(fname, "r") as f:
source_code = f.read()
# Remove shebang line if it exists.
if source_code[0:2] == "#!":
source_code = "\n".join(source_code.split("\n")[1:])
ctx = Context()
parser.parse(lexer.lex(source_code)).compile(ctx)
bytecode = ctx.create_bytecode()
frame = Frame(bytecode)
interpreter = Interpreter()
interpreter.interpret(bytecode, frame)
示例6: run
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
def run(self):
plugin_loader = PluginLoader()
plugin_directory = PluginDirectory()
commands = plugin_loader.load(plugin_directory)
interpreter = Interpreter(commands)
try:
while True:
input = self.input()
result = interpreter.interpret(input)
if result is not None:
if isinstance(result, str):
lines = result.split("\n")
if len(lines) > 1:
for line in lines:
self.output(line)
else:
self.output(result)
else:
self.output(result)
except SystemExit:
pass
示例7: InterpreterTest
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
class InterpreterTest(unittest.TestCase):
def setUp(self):
self.inter = Interpreter(RobotIO())
def listSetUp(self):
self.inter.interpret('(set list (build 4 (build 18 (build 39 []))))')
self.inter.interpret('(set meta (build list (build 3 [])))')
def test_evaluateBoolean(self):
# interpreting "True" or "False" should return the boolean
self.assertEqual(self.inter.interpret('true'), True)
self.assertEqual(self.inter.interpret('FAlsE'), False)
def test_evaluateInteger(self):
# interpreting an integer should return that integer
self.assertEqual(self.inter.interpret('3'),3)
self.assertEqual(self.inter.interpret('0'),0)
self.assertEqual(self.inter.interpret('-500'),-500)
self.assertRaises(VariableNotFoundException,self.inter.interpret,'3.5')
def test_evaluateSymbol(self):
# interpreting any non-integer/non-boolean should find that in the
# interpreter's environment
self.assertEqual(
self.inter.interpret('pi'),
self.inter.global_environment['pi'])
def test_and(self):
# boolean AND
self.assertEqual(self.inter.interpret('(and true true)'),True)
self.assertEqual(self.inter.interpret('(and true false)'),False)
self.assertEqual(self.inter.interpret('(and false false)'),False)
def test_or(self):
# boolean OR
self.assertEqual(self.inter.interpret('(or true false)'),True)
self.assertEqual(self.inter.interpret('(or false false)'),False)
self.assertEqual(self.inter.interpret('(or true true)'),True)
def test_not(self):
# boolean NOT
self.assertEqual(self.inter.interpret('(not true)'),False)
self.assertEqual(self.inter.interpret('(not false)'),True)
def test_if(self):
# boolean IF
self.assertEqual(self.inter.interpret('(if true 100 -50)'),100)
self.assertEqual(self.inter.interpret('(if false 100 -50)'),-50)
def test_plus(self):
# integer plus
self.assertEqual(self.inter.interpret('(+ 16 9)'),25)
self.assertEqual(self.inter.interpret('(+ -1000 34)'),-966)
def test_minus(self):
# integer minus
self.assertEqual(self.inter.interpret('(- 16 9)'),7)
self.assertEqual(self.inter.interpret('(- 34 -1000)'),1034)
def test_multiply(self):
# integer multiply
self.assertEqual(self.inter.interpret('(* 16 9)'),144)
self.assertEqual(self.inter.interpret('(* 34 -1000)'),-34000)
def test_divide(self):
# integer divide
self.assertEqual(self.inter.interpret('(/ 16 8)'),2)
self.assertEqual(self.inter.interpret('(/ 1000 35)'),28)
# divide by zero
self.assertRaises(ZeroDivisionError,self.inter.interpret,('(/ 2 0)'))
def test_set(self):
# setting variable to a number
self.inter.interpret('(set a 3)')
self.assertEqual(self.inter.interpret('a'),3)
# setting variable to a boolean
self.inter.interpret('(set b true)')
self.assertEqual(self.inter.interpret('b'),True)
# attempting to re-set a variable should raise an error
self.assertRaises(VariableAlreadySetException,
self.inter.interpret,'(set b 4)')
def test_define(self):
# defining a function without parameters
self.inter.interpret('(define a () 3)')
self.assertEqual(self.inter.interpret('(a)'),3)
# defining a function with a parameter
self.inter.interpret('(define b x (* x 2))')
self.assertEqual(10,self.inter.interpret('(b 5)'))
# defining a function with multiple parameters
self.inter.interpret('(define defence (banana pointedstick)' +
'(* banana pointedstick))')
self.assertEqual(21, self.inter.interpret('(defence 7 3)'))
#.........这里部分代码省略.........
示例8:
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
# We must have a HALT instruction.
for instr in memory_input:
if instr == "HALT":
memory.append(-5)
elif instr == "ADD":
memory.append(-10)
elif instr == "SUB":
memory.append(-15)
elif instr == "MULT":
memory.append(-20)
else:
if (interpreter.is_valid(int(instr))):
memory.append(int(instr))
else:
memory.append(-9)
if (memory[0] is -20):
interpreter.set_ac(1)
interpreter.interpret(memory, 0)
示例9: run
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
class Application:
input_source = KeyboardInput
def run(self):
plugin_loader = PluginLoader()
plugin_directory = PluginDirectory('core')
commands = plugin_loader.load(plugin_directory)
self._welcome()
self._init_completion(commands)
self.interpreter = Interpreter(commands)
poller = Poller(self.input_source, self.input_evaluator)
poller.poll()
def _welcome(self):
print 'Placidity ' + __init__.__version__
def _init_completion(self, commands):
# http://stackoverflow.com/questions/2046050/tab-completion-in-python-command-line-interface-how-to-catch-tab-events
# TODO: http://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input (path completion)
# Note that OS X users need to install http://pypi.python.org/pypi/readline/ for this to work!
def get_names(i):
aliases = i.aliases
return aliases if hasattr(aliases, '__iter__') else [aliases]
command_names = filter(None, chain(*map(get_names, commands)))
def complete(text, state):
for cmd in command_names:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 1
readline.parse_and_bind('tab: complete')
readline.set_completer(complete)
def input_evaluator(self, user_input):
if user_input is None:
user_input = self.input()
result = self.interpreter.interpret(user_input)
if result is not None:
if isinstance(result, str):
lines = result.split('\n')
if len(lines) > 1:
for line in lines:
self.output(line)
else:
self.output(result)
else:
self.output(result)
def output(self, result):
print result
示例10: main
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
def main(utterance, world, holding, objects, **other_params):
answers = []
answer = None
if other_params:
if "prevAnswers" in other_params:
prevAnswers = eval(json.dumps(other_params["prevAnswers"]))
answers.extend(prevAnswers)
if "answer" in other_params:
answer = eval(json.dumps(other_params["answer"]))
answers.append(answer)
# Try to parse answer to see if user wnats some other thing
if answer:
if parse(answer):
utterance = answer
answer = None
answers = []
OUT['utterance'] = utterance
world = eval(json.dumps(world))
objects = eval(json.dumps(objects))
if holding:
holding = eval(json.dumps(holding))
PhysicsInit(objects)
### -- PARSE --
trees = parse(utterance)
OUT['trees'] = [str(t) for t in trees]
if not trees:
OUT['output'] = "Parse error!"
return OUT.output()
OUT.log("Parsed!!")
### -- INTERPRET --
interpreter = Interpreter(world, holding, objects)
goals = [goal for tree in trees for goal in interpreter.interpret(tree)]
if not goals:
OUT['output'] = OUT.joinErr("interpret") or "Cannot %s!" % ' '.join(map(str,eval(json.dumps(utterance))))
return OUT.output()
OUT.log('Interpreted!!')
### -- DISAMBIGUATE --
disambiguator = Disambiguator(objects, world, answers)
OUT.goals = disambiguator.pddlGoalsDisplay(goals)
goals = disambiguator.pickGoals(goals,tree)
if not goals:
OUT['output'] = OUT.joinErr("pickGoals") or "Cannot %s!" % ' '.join(map(str,eval(json.dumps(utterance))))
return OUT.output()
OUT.log('Disambiguated!!')
OUT.goals = disambiguator.pddlGoalsDisplay([goals])
### -- PLAN --
OUT['plan'] = plan = solve(goals, world, holding, objects)
if not len(plan):
OUT['output'] = "Already done."
return OUT.output()
elif not plan:
OUT['output'] = "Planning error!"
return OUT.output()
OUT.log('Planned!!!')
OUT['output'] = "Success!"
return OUT.output()
示例11: interact
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
def interact():
itp = Interpreter()
while True:
line = raw_input(">>")
line = line.strip()
itp.interpret(line)
示例12: Main
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
class Main(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# make variables
self.voltage = 0
self.current = 0
# load gui.ui
self.ui = loadUi('../gui/gui.ui')
self.ui.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
self.ui.destroyed.connect(self.shutdown)
# show window
self.ui.show()
# make new log object
self.log = Log(self.ui)
# make new sender object
self.sender = Sender(self.ui, self.log)
# set events
self.set_events()
# initial reset
self.sender.reset()
# new listener
self.listener = Listener()
# new_data_received signal
self.listener.data_received.connect(self.new_data_received)
# start listener
self.listener.start()
# new interpreter
self.interpreter = Interpreter(self.log, self.ui)
# add tree
self.add_tree()
def add_tree(self):
# Items for tree
voltage_item = QTreeWidgetItem(["Spannung", str(self.voltage) + " V"])
self.ui.treeView.addTopLevelItem(voltage_item)
current_item = QTreeWidgetItem(["Strom", str(self.current) + " A"])
self.ui.treeView.addTopLevelItem(current_item)
power_item = QTreeWidgetItem(["Watt", "0 W"])
self.ui.treeView.addTopLevelItem(power_item)
def set_events(self):
# sendButton clicked
self.ui.sendButton.clicked.connect(lambda: self.sender.send("debug"))
# holdButton clicked
self.ui.holdButton.clicked.connect(self.log.toggle_hold)
# clearButton clicked
self.ui.clearButton.clicked.connect(self.log.clear_log)
# messageInput return pressed
self.ui.messageInput.returnPressed.connect(lambda: self.sender.send("debug"))
# sliders value changed
self.ui.voltageSlider.sliderReleased.connect(lambda: self.sender.send("slider-voltage"))
self.ui.currentSlider.sliderReleased.connect(lambda: self.sender.send("slider-current"))
# reset action
self.ui.resetActionButton.triggered.connect(self.sender.reset)
# automode checkbox
self.ui.automodeCheckbox.stateChanged.connect(lambda: self.sender.send("checkbox-automode"))
# lamp checkboxes
self.ui.lamp1Checkbox.stateChanged.connect(lambda: self.sender.send("checkbox-lamp"))
self.ui.lamp2Checkbox.stateChanged.connect(lambda: self.sender.send("checkbox-lamp"))
self.ui.lamp3Checkbox.stateChanged.connect(lambda: self.sender.send("checkbox-lamp"))
self.ui.lamp4Checkbox.stateChanged.connect(lambda: self.sender.send("checkbox-lamp"))
def new_data_received(self, text):
self.interpreter.interpret(text)
def shutdown(self):
self.listener.exit()
示例13: StateMachine
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
class StateMachine(object):
'''
This class provides the entry point for the PySCXML library.
'''
def __init__(self, source, log_function=default_logfunction, sessionid=None, default_datamodel="python", setup_session=True):
'''
@param source: the scxml document to parse. source may be either:
uri : similar to what you'd write to the open() function. The
difference is, StateMachine looks in the PYSCXMLPATH environment variable
for documents if none can be found at ".". As such, it's similar to the PYTHONPATH
environment variable. Set the PYSCXMLPATH variable to exert more fine-grained control
over the src attribute of <invoke>. self.filename and self.filedir are set as a result.
xml string: if source is an xml string, it's executed as is.
self.filedir and self.filename aren't filled.
file-like object: if source has the .read() method,
the result of that method will be executed.
@param log_function: the function to execute on a <log /> element.
signature is f(label, msg), where label is a string and msg a string.
@param sessionid: is stored in the _session variable. Will be automatically
generated if not provided.
@param default_datamodel: if omitted, any document started by this instance will have
its datamodel expressions evaluated as Python expressions. Set to 'ecmascript' to assume
EMCAScript expressions.
@param setup_session: for internal use.
@raise IOError
@raise xml.parsers.expat.ExpatError
'''
self.is_finished = False
self.filedir = None
self.filename = None
self.compiler = compiler.Compiler()
self.compiler.default_datamodel = default_datamodel
self.compiler.log_function = log_function
self.sessionid = sessionid or "pyscxml_session_" + str(id(self))
self.interpreter = Interpreter()
dispatcher.connect(self.on_exit, "signal_exit", self.interpreter)
self.logger = logging.getLogger("pyscxml.%s" % self.sessionid)
self.interpreter.logger = logging.getLogger("pyscxml.%s.interpreter" % self.sessionid)
self.compiler.logger = logging.getLogger("pyscxml.%s.compiler" % self.sessionid)
self.doc = self.compiler.parseXML(self._open_document(source), self.interpreter)
self.interpreter.dm = self.doc.datamodel
self.datamodel = self.doc.datamodel
self.doc.datamodel["_x"] = {"self" : self}
self.doc.datamodel.self = self
self.doc.datamodel["_sessionid"] = self.sessionid
self.doc.datamodel.sessionid = self.sessionid
self.name = self.doc.name
self.is_response = self.compiler.is_response
if setup_session:
MultiSession().make_session(self.sessionid, self)
# self.setIOProcessors(self.datamodel)
# def setIOProcessors(self, dm):
# dm["_ioprocessors"] = {"scxml" : {"location" : dm["_x"]["self"]},
# "basichttp" : {"location" : dm["_x"]["self"]} }
def _open_document(self, uri):
if hasattr(uri, "read"):
return uri.read()
elif isinstance(uri, basestring) and re.search("<(.+:)?scxml", uri): #"<scxml" in uri:
self.filename = "<string source>"
self.filedir = None
return uri
else:
path, search_path = get_path(uri, self.filedir or "")
if path:
self.filedir, self.filename = os.path.split(os.path.abspath(path))
return open(path).read()
else:
msg = "No such file on the PYSCXMLPATH"
self.logger.error(msg + ": '%s'" % uri)
self.logger.error("PYTHONPATH: '%s'" % search_path)
raise IOError(errno.ENOENT, msg, uri)
def _start(self):
self.compiler.instantiate_datamodel()
self.interpreter.interpret(self.doc)
def _start_invoke(self, invokeid=None):
self.compiler.instantiate_datamodel()
self.interpreter.interpret(self.doc, invokeid)
def start(self):
'''Takes the statemachine to its initial state'''
if not self.interpreter.running:
raise RuntimeError("The StateMachine instance may only be started once.")
else:
doc = os.path.join(self.filedir, self.filename) if self.filedir else ""
#.........这里部分代码省略.........
示例14: raw_input
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
# Standard Modules
import sys
import os
# Modules from the GitHub
from wit import Wit
# The chunks
from recorder import Recorder
from interpreter import Interpreter
# Constants
SECONDS = 4
if __name__ == '__main__':
# Set the Wit.AI token from an environment variable
if 'WIT_TOKEN' not in os.environ:
os.environ['WIT_TOKEN'] = raw_input("Enter your Wit.AI token: ")
witToken = os.environ['WIT_TOKEN']
# Instantiate the chunks
aRecording = Recorder(SECONDS)
anInterpreting = Interpreter()
witty = Wit(witToken)
# Run with it
audio_file = aRecording.record()
result = witty.post_speech(audio_file.getvalue())
anInterpreting.interpret(result)
# And we're done
sys.exit(0)
示例15: __init__
# 需要导入模块: from interpreter import Interpreter [as 别名]
# 或者: from interpreter.Interpreter import interpret [as 别名]
class Bottlenose:
def __init__(self, bootstrapVocabulary=False):
Concept(bootstrapVocabulary=bootstrapVocabulary)
self._contexts = [Context()]
self._context = self._contexts[0]
self._translator = Translator()
self._interpreter = Interpreter(self._context)
def tell(self, input):
JSON = self._translator.visit(grammar.parse(input))
return self.tellJSON(JSON)
def tellJSON(self, JSON):
results = self._interpreter.interpret(JSON)
self._context.ponderRecentMentions()
if isinstance(results, set) or isinstance(results, list):
objects = list()
for result in results:
objects.append(BottlenoseObject(result, self._context))
return objects
elif not results:
return None
else:
return [BottlenoseObject(results, self._context)]
def ask(self, subject, clause=None):
query = "?" + subject
if clause:
query += "(" + clause + ")"
return self.tell(query)
def context(self):
return self._context
def listContexts(self):
return self._contexts
def setContext(self, index):
if index >= 0 and index < len(self._contexts):
self._context = self._contexts[index]
self._interpreter.setContext(self._contexts[index])
def loadFile(self, filePath, onlyBeliefs=False, onlyStatements=False):
file = open(filePath, 'r')
for line in file:
line = line.rstrip("\n")
JSON = self._translator.visit(grammar.parse(line))
if 'statement' in JSON:
if not onlyBeliefs:
self.tellJSON(JSON)
else:
if not onlyStatements:
self.tellJSON(JSON)
def loadDirectory(self, dirPath):
filePaths = []
for root, dirnames, filenames in os.walk(dirPath):
for filename in fnmatch.filter(filenames, '*.bottle'):
filePaths.append(os.path.join(root, filename))
for filePath in filePaths:
self.loadFile(filePath, onlyBeliefs=True)
for filePath in filePaths:
self.loadFile(filePath, onlyStatements=True)