【问题标题】:What's the most efficient way to pause a CPU-intensive python program?暂停 CPU 密集型 python 程序的最有效方法是什么?
【发布时间】:2018-04-15 10:34:24
【问题描述】:

我制作了一个实时分析屏幕截图的神经网络(不幸的是,它变得越来越复杂,并且变得相当 CPU 密集型)。

我希望在按下字母“a”时暂停它,并在再次按下字母“a”时取消暂停。暂停它的最有效方法是什么(不完全打破循环)?

它使用 Python OpenCV 库,但我不使用 cv2.imshow,因此我不能使用 cv2.Waitkey。我在 Windows 10 上运行它。您能否提供示例代码来回答您的问题?代码如下:

import cv2
import mss
from PIL import Image
import numpy as np

#Creates an endless loop for high-speed image acquisition...
while (True):
    with mss.mss() as sct:
        # Get raw pixels from the screen
        sct_img = sct.grab(sct.monitors[1])

        # Create the Image
        img = Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX')

        #The rest of the neural network goes here...

        #PAUSE statement... 

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    使用 Python 标准库中 signal package 中的 sigwaitsigwait 无法在 Windows 上运行。

    编辑

    您可以使用threading library 以独立于平台的方式做您想做的事。这是一个简短的示例程序(如果您在 Linux 或 Mac 上运行,则需要 py-getch 包):

    import os
    from threading import Thread, Event
    
    if os.name=='nt':
        from msvcrt import getch
    elif os.name=='posix':
        from getch import getch
    else:
        raise OSError
    
    isRunning = True
    
    def count(event):
        i = 0
        while isRunning:
            event.wait(1)
    
            if event.isSet() and isRunning:
                event.clear()
                print('Pausing count at %d' % i)
                event.wait()
                print('resuming count')
                event.clear()
    
            i += 1
    
    def listener(event):
        # in Python, need to mark globals if writing to them
        global isRunning
    
        while isRunning:
            c = getch()
            if c=='a':
                event.set()
            if c=='e':
                event.set()
                isRunning = False
    
    def main():
        pauseEvent = Event()
        pauseEvent.clear()
    
        listenerThread = Thread(target=listener, args=(pauseEvent,))
    
        listenerThread.start()
        count(pauseEvent)
    
    if __name__=='__main__':
        main()
    

    上面的程序将运行两个线程。主线程将运行count 函数,该函数每秒将计数加1。另一个线程运行listener 函数,它将等待用户输入。如果键入alistener 线程将告诉count 线程暂停并打印出当前计数。您可以再次输入a 以恢复计数,也可以输入e 以退出。

    【讨论】:

    • 我应该指定我之前使用的是 Windows。 'sigwait' 的帮助文件指出它仅在 Unix 上可用。
    • @MonkeyBot2020 您可以使用 Python 中的线程库来实现自己的(有限的)自定义信号处理。我在答案中添加了一个示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    相关资源
    最近更新 更多