How to timeout regex methods?

Viewed 100

I'm using several methods of regex module. I need to set timeouts for multiple compiled patterns, but despite example from docs, I'm unable to reproduce an exception doing the following:

>>> import regex
>>> from time import sleep
>>> def slow_replace(m):
...     sleep(5)
...     return 'X'
...
>>> regex.sub(r'[a-z]', slow_replace, 'abcde', timeout=2)

It does not raise TimeoutError as expected.

I'm using python 3.8 on Ubuntu 20.04 LTS within Microsoft WSL2. I also found this related issue, but it did not help. How can I work around that issue?

1 Answers

On mac os

import regex
import time
from time import sleep
def slow_replace(m):
    start = time.time()
    i = 0 
    while time.time()-start < 10:
        i += 1
    return 'X'

regex.sub(r'[a-z]', slow_replace, 'abcde', timeout=2)

raises a TimeoutError as expected.

Related