0

I would like set a limit time for process in python, because this process doesn't end with itself. It is something like this:

def forever():
    pass

somethink_to_do_this_20_secounds:
    forever()

print("this print after 20 seconds of forever() work")

I found a topic about checking program execution time, but I did not find setting the time limit for the program How do I get time of a Python program's execution?

How i can realize this somethink_to_do_this_20_secounds in Python? By using subprocess?

Cierniostwor
  • 339
  • 2
  • 4
  • 15

1 Answers1

1

You could use the concurrent module to fire a separate thread and wait for it 20 seconds.

from concurrent.futures import ThreadPoolExecutor, TimeoutError
from time import sleep


def forever():
    sleep(21)

pool = ThreadPoolExecutor()
future = pool.submit(forever)
try:
    result = future.result(20)
except TimeoutError:
    print("Timeout")

print("this print after 20 seconds of forever() work")