2

I'm using multiprocessing to display screenshots 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
1
  • 2
    Because it imports pygame separately on each process Commented Jun 17, 2022 at 21:28

1 Answer 1

1

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
  ...
Sign up to request clarification or add additional context in comments.

2 Comments

So how do I import for specify process only in a function? In this case function displayer is only need pygame. While grabber doesn't need it. Should I import inside function?
See my updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.