Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely run unreliable piece of code?

Suppose you are working with some bodgy piece of code which you can't trust, is there a way to run it safely without losing control of your script?

An example might be a function which only works some of the time and might fail randomly/spectacularly, how could you retry until it works? I tried some hacking with using threading module but had trouble to kill a hung thread neatly.

#!/usr/bin/env python

import os
import sys
import random

def unreliable_code():

  def ok():
    return "it worked!!"

  def fail():
    return "it didn't work"

  def crash():
    1/0

  def hang():
    while True: 
      pass

  def bye():
    os._exit(0)

  return random.choice([ok, fail, crash, hang, bye])()


result = None
while result != "it worked!!":
  # ???
like image 647
wim Avatar asked Mar 21 '12 11:03

wim


2 Answers

To be safe against exceptions, use try/except (but I guess you know that).

To be safe against hanging code (endless loop) the only way I know is running the code in another process. This child process you can kill from the father process in case it does not terminate soon enough.

To be safe against nasty code (doing things it shall not do), have a look at http://pypi.python.org/pypi/RestrictedPython .

like image 147
Alfe Avatar answered Oct 24 '22 00:10

Alfe


You can try running it in a sandbox.

like image 4
root Avatar answered Oct 23 '22 23:10

root