Home > Net >  Python imports multiple times when using multiprocessing Process
Python imports multiple times when using multiprocessing Process

Time:06-18

I'm using multiprocessing to display screenshot with the mss module from pygame. However, the hello message is displayed three times.

I'm wondering if this will distract performance. Also when I close the screen of pygame the console keeps on running. Here is my code:

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()

So if you run this it will run perfectly, but will display the community message three times:

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

CodePudding user response:

When you run Process with a method from the same file, you basically have the same imports: once for the main script, and twice more for each Process instance.

You can move the import ... statements under the specific method. For example:

def displayer(queue: Queue):
  import pygame
  ...
  • Related