How to limit execution time of a function call in Python

后端 未结 10 1929
遥遥无期
遥遥无期 2020-11-22 10:25

There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which

10条回答
  •  再見小時候
    2020-11-22 11:12

    The method from @user2283347 is tested working, but we want to get rid of the traceback messages. Use pass trick from Remove traceback in Python on Ctrl-C, the modified code is:

    from contextlib import contextmanager
    import threading
    import _thread
    
    class TimeoutException(Exception): pass
    
    @contextmanager
    def time_limit(seconds):
        timer = threading.Timer(seconds, lambda: _thread.interrupt_main())
        timer.start()
        try:
            yield
        except KeyboardInterrupt:
            pass     
        finally:
            # if the action ends in specified time, timer is canceled
            timer.cancel()
    
    def timeout_svm_score(i):
         #from sklearn import svm
         #import numpy as np
         #from IPython.core.display import display
         #%store -r names X Y
         clf = svm.SVC(kernel='linear', C=1).fit(np.nan_to_num(X[[names[i]]]), Y)
         score = clf.score(np.nan_to_num(X[[names[i]]]),Y)
         #scoressvm.append((score, names[i]))
         display((score, names[i])) 
         
    %%time
    with time_limit(5):
        i=0
        timeout_svm_score(i)
    #Wall time: 14.2 s
    
    %%time
    with time_limit(20):
        i=0
        timeout_svm_score(i)
    #(0.04541284403669725, '计划飞行时间')
    #Wall time: 16.1 s
    
    %%time
    with time_limit(5):
        i=14
        timeout_svm_score(i)
    #Wall time: 5h 43min 41s
    

    We can see that this method may need far long time to interrupt the calculation, we asked for 5 seconds, but it work out in 5 hours.

提交回复
热议问题