繁体   English   中英

Python:停止执行 function

[英]Python: Stop function from execution

我的任务如下:

  1. 按键盘上的 F
  2. 在另一个脚本中执行 function
  3. 在键盘上再次按 F 并停止执行我刚刚启动的脚本。
  4. 也许再次按 F 并重新开始。

为了方便起见,我写了一个 function PrintNumbers.py 我不想陷入永远循环,所以我在数到 10 后停止 function。实际上,我希望我的代码永远执行,直到我告诉它停止。

import time

global stopnow
stopnow = False

def stopPrinting():
    global stopnow
    stopnow = True
    
def PrintNumbers():
    global stopnow
    x = 0
    while (x < 10) and not stopnow:
        x = x + 1
        #if x == 5:
        #    stopPrinting()
        print('X is: %s\Stopnow is %s' % (x, stopnow))
        time.sleep(1)

    
if __name__ == "__main__":
    PrintNumbers()

现在我尝试从另一个文件main.py调用它:

import keyboard
import time
import PrintNumbers as pN
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
IsPressed = False
# once you press the button('f') the function happens once
# # when you release the button('f') the loop resets

while True:
    if not keyboard.is_pressed('f'):
        IsPressed = False
        pN.stopnow
    while not IsPressed:
        if keyboard.is_pressed('f'): 
            print('pN now counting to 10!')
            IsPressed = True
            pN.PrintNumbers()

所以 - 我明白了,我“解雇并忘记”我的 pN.Printnumbers,但我在万维网中找不到一个如何解决这个问题的例子。

我什至在 TkInter 上花了几个小时来使用开始和停止按钮来完成这项工作,结果却发现我的主循环在执行过程中冻结了。 即使线程不起作用,我也很沮丧。

真心期待您的支持。

PS:我很想看到并非常感谢复制和粘贴解决方案,这样我就可以自己尝试并理解你们专家的建议。

亲切的问候,克里索!

正如您所概述的,有几种方法可以与 function 进行交互。 使用 Tkinter 会增加一定程度的复杂性,因为您必须处理 GUI 线程,但这还不错。 我将在 tkinter 中使用绑定展示一个示例:

from tkinter import *

class App(Tk): #Main window
    def __init__(self):
        Tk.__init__(self)
        self.output = False
        self.num = 0
        self.text = Text(self)
        self.text.pack()
        self.bind('<f>', self.OnKeyPress) #The bind creates a link between pressing f and "App.OnKeyPress"
        self.NumberOutput()

    def NumberOutput(self):
        if self.output:
            self.text.insert('end', str(self.num))
            self.num += 1
        self.after(1000, self.NumberOutput) #using after(ms, function) keeps the GUI from locking

    def OnKeyPress(self, event):
        self.output = not self.output
        self.num = 0

if __name__ == '__main__':
    app = App()
    app.mainloop()

我将把它作为一个练习,将数字内容移动到它自己的脚本文件中。

注意:您可以使用 bind 绑定到任何 function ,而不仅仅是 App.

我的代码太长,无法发表评论,因此我将其发布为答案。

这是我对 Tkinter 和一个过程的尝试。

from tkinter import *
import time
import PrintNumbers as pN
from multiprocessing import Process, Queue   

#################
# Main Functions
#################

def clickedStart():
    #pN.PrintNumbers()
    
    myProcess1 = Process(target=pN.PrintNumbers(), args=())
    myProcess1.start()   
    print(f'Process1 is alive: {myProcess1.is_alive()}')
    myProcess1.kill()
    time.sleep(1)
    print(f'Process1 is still alive: {myProcess1.is_alive()}')
    
#################
# TK Inter Design
#################
window = Tk()
window.title("Start/Stop Counting")

#window.geometry('350x200')

startbtn = Button(window, text="Start",command=lambda: clickedStart())
startbtn.grid(column=1, padx=20,pady=20,row=0)
stopbtn = Button(window, text="Stop")
stopbtn.grid(column=3, padx=20,row=0)

global queue
queue = Queue()

window.mainloop()

但是,我的 Tkinter Windows 完全冻结,直到该过程完成。 我不能移动 window,我不能点击停止 - 什么都没有。

暂无
暂无

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

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