【问题标题】:How to add a pause in python without disrupting other code如何在 python 中添加暂停而不破坏其他代码
【发布时间】:2021-01-06 21:27:38
【问题描述】:

我正在尝试制作一个脚本,通过文本记录游戏中每个老板的时间。

一个例子是:

if line == 'boss1 down':
    print('boss1 timer set for 10 seconds')
    time.sleep(10)
    print("boss1 due")

if line == 'boss2 down':
    print('boss2 timer set for 15 seconds')
    time.sleep(15)
    print("boss2 due")

但是,明显的问题是一次只能对一个老板进行计时。有没有我可以使用的功能不会破坏代码并允许我在给定时间多次计时?

【问题讨论】:

  • 我认为您正在寻找的是多线程。你可以阅读它here

标签: python multiprocessing


【解决方案1】:

您可以使用内置threading 模块中的Thread 类:

from threading import Thread
import time

def timer(num, secs, line):
    if line == f'boss{num} down':
        print(f'boss{num} timer set for {secs} seconds ')
        time.sleep(secs)
        print(f"boss{num} due")

boss1 = Thread(target=timer, args=(1, 10, "boss1 down"))
boss2 = Thread(target=timer, args=(2, 15, "boss2 down"))

boss1.start()
boss2.start()

输出:

boss1 timer set for 10 seconds boss2 timer set for 15 seconds

boss1 due
boss2 due

【讨论】:

    【解决方案2】:

    你可以使用Asynchronous函数:

    import asyncio
    
    async def boss1_down():
        print('boss1 timer set for 10 seconds')
        await asyncio.sleep(10)
        print("boss1 due")
    asyncio.run(boss1_down())
    

    ,为定时器和老板的函数添加参数。

    正如@Mayank 提到的,您也可以使用threads,虽然解决起来有点复杂,但您可以控制它们(您不能停止或等待async 函数)。

    【讨论】:

      【解决方案3】:

      来自answer

      你可以使用threading来做异步任务。

      from threading import Thread
      from time import sleep
      
      def threaded_function(line):
          if line == 'boss1 down':
              print('boss1 timer set for 10 seconds')
              time.sleep(10)
              print("boss1 due")
          if line == 'boss2 down':
               print('boss2 timer set for 15 seconds')
               time.sleep(15)
               print("boss2 due")
      
      if __name__ == "__main__":
          thread1 = Thread(target = threaded_function, args= 'boss1 down')
          thread1.start()
          thread1.join()
      
          thread2 = Thread(target = threaded_function, args= 'boss2 down')
          thread2.start()
          thread2.join()
          print("thread finished...exiting")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-06
        • 2021-09-12
        • 1970-01-01
        • 2020-12-13
        • 2012-12-21
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        相关资源
        最近更新 更多