Skip to content

Instantly share code, notes, and snippets.

@readevalprint
Last active January 22, 2019 06:32
Show Gist options
  • Save readevalprint/930268 to your computer and use it in GitHub Desktop.
Save readevalprint/930268 to your computer and use it in GitHub Desktop.
import sys, shutil, os, tempfile
from cStringIO import StringIO
TIMEOUT = 5
# SANDBOX_BIN = '/usr/bin/pypy-sandbox'
SANDBOX_BIN = '/home/ubuntu/pypy/pypy/goal/pypy-c' # update this for you
sys.path = [ '/home/ubuntu/pypy'] + sys.path
# import pypy now that it's added to the path
from pypy.sandbox import pypy_interact
def exec_sandbox(code):
try:
#tmpdir = tempfile.mkdtemp()
#tmpscript = open(os.path.join(tmpdir, "script.py"),'w') # script.py is the name of the code passed in
#tmpscript.write(code)
#tmpscript.close()
sandproc = pypy_interact.PyPySandboxedProc(
SANDBOX_BIN,
['-c', code] # un comment this and comment the next line if you want to run code directly
#['/tmp/script.py','--timeout',str(TIMEOUT),],
#tmpdir # this is dir we jsut made that will become /tmp in the sandbox
)
try:
code_output = StringIO()
code_log = StringIO()
sandproc.interact(stdout=code_output, stderr=code_log)
return code_output.getvalue(), code_log.getvalue()
except Exception, e:
sandproc.kill()
finally:
sandproc.kill()
shutil.rmtree(tmpdir)
except Exception, e:
pass
return 'Error, could not evaluate', e
code = '''
print 'Hi there!'
1/0 # watch for the line number!
# Next, try to list the system files and write to one.
'''
out, err = exec_sandbox(code)
print '=' *10
print 'OUTPUT\n%s' % out
print '=' *10
print 'ERRORS\n%s' % err
$ hg clone https://bitbucket.org/pypy/pypy
$ cd pypy/pypy
$ pypy ../../rpython/bin/rpython -O2 --sandbox targetpypystandalone  
==========
OUTPUT
Hi there!
==========
ERRORS
Traceback (most recent call last):
File "app_main.py", line 53, in run_toplevel
File "/tmp/script.py", line 4, in <module>
1/0 # watch for the line number!
ZeroDivisionError: integer division by zero
[Subprocess exit code: 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment