Created
December 9, 2011 18:31
-
-
Save jl2/1452718 to your computer and use it in GitHub Desktop.
Command line Javascript REPL using QtScript. If given a filename argument, runs the file and exits.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
from PyQt4 import QtCore | |
from PyQt4.QtScript import QScriptEngine, QScriptValue | |
def my_exit(context, eng): | |
exit(0) | |
def my_print(context, eng): | |
if context.argumentCount() == 0: | |
print("") | |
else: | |
na = context.argumentCount() | |
args = list() | |
for i in range(na): | |
args.append( str(context.argument(i).toVariant())) | |
pval = ' '.join(args) | |
global show_val | |
print(pval) | |
return QScriptValue("Okay") | |
def do_repl(qse): | |
curScript = '' | |
while(True): | |
if len(curScript)>0: | |
prompt = '... ' | |
else: | |
prompt = '>>> ' | |
print(prompt, end='') | |
curScript += input() | |
if QScriptEngine.checkSyntax(curScript).state() != 1: | |
res = qse.evaluate(curScript) | |
if res.isError(): | |
if res.property("expressionBeginOffset").toVariant() is not None: | |
off1 = int(res.property("expressionBeginOffset").toVariant()) | |
else: | |
off1 = 0 | |
if res.property("expressionEndOffset").toVariant() is not None: | |
off2 = int(res.property("expressionEndOffset").toVariant()) | |
else: | |
off2 = len(curScript) | |
print("Syntax error at:") | |
print(' ' + curScript) | |
print(' ', end='') | |
for i in range(off1): | |
print(' ', end='') | |
for i in range(off2-off1): | |
print('^', end='') | |
print('') | |
curScript = '' | |
def main(args): | |
app = QtCore.QCoreApplication(args) | |
qse = QScriptEngine() | |
mef = qse.newFunction(my_exit) | |
qse.globalObject().setProperty('exit', mef) | |
pf = qse.newFunction(my_print) | |
qse.globalObject().setProperty('print', pf) | |
if len(args)==0: | |
do_repl(qse) | |
script = '' | |
with open(args[0]) as inf: | |
script = inf.read() | |
rv = qse.evaluate(script) | |
if __name__=='__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment