我使用多处理来显示pygamemss个模块的屏幕截图.但是,hello消息会显示三次.

我想知道这是否会分散表演的注意力.当我关闭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

推荐答案

当您使用来自同一文件的方法运行Process时,基本上有相同的导入:一次用于主脚本,两次用于每个Process实例.

您可以将import ...条语句移动到特定方法下.例如:

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

Python相关问答推荐

Pandas 有条件轮班操作

运行Python脚本时,用作命令行参数的SON文本

在Python中管理打开对话框

如果值发生变化,则列上的极性累积和

如何在WSL2中更新Python到最新版本(3.12.2)?

梯度下降:简化要素集的运行时间比原始要素集长

部分视图的DataFrame

如何在UserSerializer中添加显式字段?

Pandas Loc Select 到NaN和值列表

未调用自定义JSON编码器

搜索按钮不工作,Python tkinter

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?

从一个df列提取单词,分配给另一个列

应用指定的规则构建数组

SpaCy:Regex模式在基于规则的匹配器中不起作用

BeatuifulSoup从欧洲志愿者服务中获取数据和解析:一个从EU-Site收集机会的小铲子

如果服务器设置为不侦听创建,则QWebSocket客户端不连接到QWebSocketServer;如果服务器稍后开始侦听,则不连接

Python:在cmd中添加参数时的语法

在Django REST框架中定义的URL获得404分

保存由PYTHON在EXCEL中所做更改的问题