Python 在使用多处理 Process 时会多次导入

问题描述 投票:0回答:1

我正在使用多重处理来显示来自

mss
pygame
模块的屏幕截图。但是,问候消息显示了 3 次。

我想知道这是否会分散性能。另外,当我关闭“pygame”屏幕时,控制台会继续运行。这是我的代码:

from mss import mss
from multiprocessing import Process, Queue
import pygame
import pygame.display
import pygame.image
import pygame.time
import pygame.font
import pygame.event
from pygame.locals import *
from numpy import asarray
from cv2 import resize, cvtColor, COLOR_BGRA2BGR

SCR_SIZE = (640, 480)

def grabber(queue: Queue):
  global SCR_SIZE
  with mss() as sct:
    while True:
      queue.put(cvtColor(resize(asarray(sct.grab(sct.monitors[1])), SCR_SIZE), COLOR_BGRA2BGR).tobytes())

def displayer(queue: Queue):
  global SCR_SIZE
  pygame.init()
  SCR = pygame.display.set_mode(SCR_SIZE, DOUBLEBUF)
  SCR.set_alpha(None)
  clock = pygame.time.Clock()
  FONT_COMIC = pygame.font.SysFont('Cambria Math', 20)
  isGameRunning = True
  while isGameRunning:
    for EVENT in pygame.event.get():
      if EVENT.type == pygame.QUIT:
        isGameRunning = False
    clock.tick(60)
    currentFrame = queue.get()
    if currentFrame is not None:
      SCR.blit(pygame.image.frombuffer(currentFrame, SCR_SIZE, 'BGR'), (0,0))
    else:
      break
    SCR.blit(FONT_COMIC.render('FPS:'+str(clock.get_fps())[:5], False, (0,255,0)),(10,10))
    pygame.display.update()


if __name__ == "__main__":
  queue = Queue()
  Process(target=grabber, args=(queue,)).start()
  Process(target=displayer, args=(queue,)).start()

因此,如果您运行此命令,它将完美运行,但会显示社区消息三次:

pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
python pygame multiprocessing
1个回答
1
投票

当您使用同一文件中的方法运行

Process
时,您基本上具有相同的导入:主脚本一次,每个
Process
实例两次。

您可以将

import ...
语句移动到特定方法下。例如:

def displayer(queue: Queue):
  import pygame
  ...
© www.soinside.com 2019 - 2024. All rights reserved.