Entries Projects About

 Breaking code after specified period of time

3 March 2018, (Updated 7 June)

After quite long break, I come with idea about breaking function after specific period of time.

Actually in Python there is library signal that we can use to achieve this effect by creating function that will be called after specified period of time, and that function can rise an exception that we will able to catch so that to support situation when code will run out of a time. (link to example of this solution on github).

But I'd like to have something more transparent and more convenient in usage. So that, I wrote small module for that, this code is based on threading library, I had to make some changes in returning values from threads. Because by default .join method doesn't return value from thread.

But in the end I packed everything into one function named sandbox.

Below some examples of usage my sanbox function.

def test_function(a=None, b=None, c=None):
    >>> test_function('X', 'Y', 'Z')
    ['Z', 'Y', 'X']
    >>> test_function()
    [None, None, None]
    #print(a, b, c)
    return [c, b, a]

print(sandbox(test_function, 5, ['A', 'B', 'C']))
# ('Function finished correctly', ['C', 'B', 'A'])
print(sandbox(test_function, 0.1, ['A', 'B', 'C']))
# Function forcibly killed
print(sandbox(test_function, 0.1))
# Function forcibly killed

Update 1, (7 June 2018)
Actually some time ago I noticed here error, namely if script goes further function 'test_function' on sub-thread is still working on, to manage this situation we have to additionaly check result from function and respectively react.

Source code:
Github Breaking code after specified period of time


Miscellaneous © 2014-2017-2018