【问题标题】:running the script through the specified time in python在python中通过指定时间运行脚本
【发布时间】:2021-07-22 20:29:48
【问题描述】:

我想在指定时间内在列表中输入一个值。例如,我想在 5 分钟内在一个空列表中输入一个值,但我希望能够在 5 分钟内完成此操作。 5分钟结束后,我想在屏幕上打印“时间结束”。我怎样才能做到这一点?我不能使用 time.sleep() 因为当我使用它时,python 进入睡眠状态,此时我无法输入数据。简而言之,我希望我的脚本运行 5 分钟。完成,当 5 分钟结束时。我怎样才能做到这一点? 谢谢。

【问题讨论】:

  • 我建议研究更广泛的并发方面。 python 线程模块可能是完成任务的最简单方法...
  • 运行一个无限的while True 循环并在时间到时中断。
  • @ThePyGuy 如果直接使用input 并且非阻塞输入将不会退出,则会无缘无故地将核心固定为 100%。
  • 是的,我知道,并且事件循环可以用于那些即使进程正在等待用户输入也只会检查条件的情况。
  • @TeejayBruno 我现在研究一下,谢谢先生。

标签: python list time


【解决方案1】:

一个简单的方法是使用多处理包。让一个新进程休眠 5 秒钟,然后让主进程完成这项工作。共享状态变量可用于通知主进程何时停止。

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

您可以查看文档了解更多详情:https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes

【讨论】:

    【解决方案2】:

    为了实现您的目标,您可以使用 asyncio 对异步函数进行超时。

    您必须首先包装阻塞 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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 2012-12-30
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 2015-10-06
      相关资源
      最近更新 更多