How to safely run unreliable piece of code?

前端 未结 3 1878
遇见更好的自我
遇见更好的自我 2020-12-31 16:54

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 mig

相关标签:
3条回答
  • 2020-12-31 17:40

    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 .

    0 讨论(0)
  • 2020-12-31 17:56

    In your real case application can you switch to multiprocessing? Becasue it seems that what you're asking could be done with multiprocessing + threading.Timer + try/except.

    Take a look at this:

    class SafeProcess(Process):
        def __init__(self, queue, *args, **kwargs):
            self.queue = queue
            super().__init__(*args, **kwargs)
        def run(self):
            print('Running')
            try:
                result = self._target(*self._args, **self._kwargs)
                self.queue.put_nowait(result)
            except:
                print('Exception')
    
    result = None
    while result != 'it worked!!':
        q = Queue()
        p = SafeProcess(q, target=unreliable_code)
        p.start()
        t = Timer(1, p.terminate)   # in case it should hang
        t.start()
        p.join()
        t.cancel()
        try:
            result = q.get_nowait()
        except queues.Empty:
            print('Empty')
        print(result)
    

    That in one (lucky) case gave me:

    Running
    Empty
    None
    Running
    it worked!!
    

    In your code samples you have 4 out of 5 chances to get an error, so you might also spawn a pool or something to improve your chances of having a correct result.

    0 讨论(0)
  • 2020-12-31 18:02

    You can try running it in a sandbox.

    0 讨论(0)
提交回复
热议问题