简体   繁体   English

在python中通过指定的时间运行脚本

[英]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.例如,我想在 5 分钟内在空列表中输入一个值,但我希望能够在 5 分钟内执行此操作。 When 5 minutes are over, I want to print "time is over" on the screen. 5 分钟结束后,我想在屏幕上打印“时间结束”。 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.我不能使用 time.sleep() 因为当我使用它时,python 进入睡眠状态,我无法在那个时候输入数据。 So in short, I want my script to run for 5 minutes.简而言之,我希望我的脚本运行 5 分钟。 Finish, when 5 minutes are over.完成,当 5 分钟结束。 How can I do that?我怎样才能做到这一点? Thank you.谢谢你。

To achieve your goal, you can timeout on asynchronous functions using asyncio.为了实现您的目标,您可以使用 asyncio 在异步函数上超时。

You have to wrap the blocking input function first but Python has first class support for everything to do with async.您必须首先包装阻塞input函数,但 Python 对与异步有关的所有事情都有一流的支持。

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())

A simple approach is to use the multiprocessing package.一个简单的方法是使用 multiprocessing 包。 Have a new process to sleep for 5 seconds and let the main one doing the job.让一个新进程休眠 5 秒钟,然后让主要进程完成工作。 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您可以查看文档以获取更多详细信息: https : //docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM