Skip to content

Instantly share code, notes, and snippets.

@tuxmartin
Last active December 27, 2016 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxmartin/e6bda67f293990f7e1ad54b0f3202ec0 to your computer and use it in GitHub Desktop.
Save tuxmartin/e6bda67f293990f7e1ad54b0f3202ec0 to your computer and use it in GitHub Desktop.
Embedding JavaScript into Python
/usr/bin/python3.5 /home/martin/PycharmProjects/JavaScript/miniracer_test1.py
2
89
:-)
Timed out!
Process finished with exit code 0
Kdysi jsem delal neco podobneho v Jave: http://pastebin.com/e86AGMau
# https://blog.sqreen.io/embedding-javascript-into-python/
# http://stackoverflow.com/a/366763/1974494
# http://stackoverflow.com/a/601168/1974494
import signal
from contextlib import contextmanager
from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
# ---------------------
print( ctx.eval('1+1') )
# ---------------------
my_script_1 = """
function maxNumber(arr) {
var largest = arr[0];
for (var i = 0; i < arr.length; i++) {
if (largest < arr[i] ) {
largest = arr[i];
}
}
return largest;
}
"""
ctx.eval(my_script_1)
arr = [3, 6, 2, 56, 32, 5, 89, 32]
max = ctx.call("maxNumber", arr)
print(max)
# ---------------------
my_script_2 = """
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + (delay * 1000));
return ":-)";
}
"""
ctx.eval(my_script_2)
class TimeoutException(Exception): pass
@contextmanager
def time_limit(seconds):
def signal_handler(signum, frame):
raise TimeoutException("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
try:
with time_limit(5):
result = ctx.call("sleep", 3)
print(result)
except TimeoutException as msg:
print("Timed out!")
try:
with time_limit(5):
result = ctx.call("sleep", 7)
print(result)
except TimeoutException as msg:
print("Timed out!")
# ---------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment