Last active
December 27, 2016 00:17
-
-
Save tuxmartin/e6bda67f293990f7e1ad54b0f3202ec0 to your computer and use it in GitHub Desktop.
Embedding JavaScript into Python
This file contains 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/python3.5 /home/martin/PycharmProjects/JavaScript/miniracer_test1.py | |
2 | |
89 | |
:-) | |
Timed out! | |
Process finished with exit code 0 |
This file contains 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
Kdysi jsem delal neco podobneho v Jave: http://pastebin.com/e86AGMau |
This file contains 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
# 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