【问题标题】:How to stop a function in python?如何停止python中的函数?
【发布时间】:2022-01-21 18:32:45
【问题描述】:

我想停止该函数,以便运行另一个函数,这是我的代码:

from pynput import keyboard
import os, sys
import pygame
import time
from pygame import mixer
from pynput import mouse
from pygame import mixer
pygame.mixer.init(buffer=10)
from pynput.keyboard import Key, Listener

def click0():
    def on_press(key):
        print("HARD CLICK")

def click1():
    def on_press(key):
        print("MEM CLICK")

def click2():
    def on_press(key):
        print("SOFT CLICK")


# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

while True:
    click0()
    time.sleep(1) #sleep for 1 second
    click1()
    time.sleep(2) #sleep for 1 second
    click2()

我希望它是这样的:

from pynput import keyboard
import os, sys
import pygame
import time
from pygame import mixer
from pynput import mouse
from pygame import mixer
pygame.mixer.init(buffer=10)
from pynput.keyboard import Key, Listener

def click0():
    def on_press(key):
        print("HARD CLICK")

def click1():
    def on_press(key):
        print("MEM CLICK")

def click2():
    def on_press(key):
        print("SOFT CLICK")


# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

while True:
    click0()
    time.sleep(1) #sleep for 1 second
    click0(quit)
    click1()
    time.sleep(2) #sleep for 1 second
    click1(quit)
    click2()

所以我想编写具有 3 个功能的代码,它轮流循环,例如:click1(正在循环)、click2(正在循环)、click3(正在循环)、click1(正在循环)、click..

但我想在运行不同的功能之前停止该功能:click1(正在循环),click1(停止)click2(正在循环),click2(停止)click3(正在循环),click3(停止)单击.. 请问有什么帮助吗?

【问题讨论】:

    标签: python function click


    【解决方案1】:

    考虑使用异步和返回运算符:

    async def click0():
      #.. do things
      return 
    
    async def click1():
      #.. do things again
      return 
    
    async def main():
      while True:
          await click0()
          await click1()
    

    这个 await 方法本质上是等到一个函数完成后再移动到下一行,所以这里 click0 函数需要在 click1() 执行之前完成,

    或者,您可以从 click0 调用 click1,从 click1 调用 click2,依此类推...

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 2018-08-15
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2018-05-25
      • 1970-01-01
      相关资源
      最近更新 更多