How to safely run unreliable piece of code?

前端 未结 3 1884
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题