xentry
xentry

Reputation: 3

running the script through the specified time in python

I want to enter a value in a list within a specified time. For example, I want to enter a value in an empty list within 5 minutes, but I want to be able to do this for 5 minutes. When 5 minutes are over, I want to print "time is over" on the screen. How can I do that? I can't use time.sleep() because when I use it, python goes to sleep and I can't enter data at that moment. So in short, I want my script to run for 5 minutes. Finish, when 5 minutes are over. How can I do that? Thank you.

Upvotes: 0

Views: 60

Answers (2)

panpsim
panpsim

Reputation: 26

A simple approach is to use the multiprocessing package. Have a new process to sleep for 5 seconds and let the main one doing the job. A shared state variable can be used to notify the main process when to stop.

from multiprocessing import Process, Value
import time

def wait(stop_value, num_of_seconds):
    print('wait called...')
    time.sleep(num_of_seconds)
    stop_value.value = True

if __name__ == '__main__':
    print('Starting...')
    v_stop = Value('b', False)
    p = Process(target=wait, args=(v_stop, 5,) )
    p.start()
    counter = 0
    while not v_stop.value:
        print(counter)
        time.sleep(1)
        counter = counter + 1
    print('Finished')

You may check the docs for more details: https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes

Upvotes: 0

Kaihaku
Kaihaku

Reputation: 149

To achieve your goal, you can timeout on asynchronous functions using asyncio.

You have to wrap the blocking input function first but Python has first class support for everything to do with async.

import asyncio


async def ainput(prompt):
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(None, input, prompt)

async def main():
    try:
        text = await asyncio.wait_for(ainput('Enter something in under 5 seconds: '), timeout=5)
        print(f'{text=}')
    except asyncio.TimeoutError:
        print('\ntime is up!')

if __name__ == '__main__':
    asyncio.run(main())

Upvotes: 0

Related Questions