首页 > 解决方案 > 为什么某些代码在 python 进程中的函数中不起作用?

问题描述

在我的脚本中,我注意到我的一些代码没有运行。例如,在我的“count()”函数中,frames.append(frame) 没有运行。我知道它没有运行,因为我得到了一个空的 MKV 文件,而且我的名为“帧”的列表中没有任何内容。除了没有运行之外,如果我将“ifkeyboard.is_pressed('q'):”放在 count 函数中,它就不会执行。

import cv2 as cv
import numpy as np
import pyautogui
import keyboard
# For other stuff
from pydub import AudioSegment
from pydub.playback import play
import pyaudio
import wave
import moviepy.editor as mpe
import sounddevice as sd
from scipy.io.wavfile import write
from multiprocessing import Pool
from multiprocessing import Process
import multiprocessing as mp
import time
import os
import sys

y = 0
frames = []       
z = 0


# Variables for 'count()'
x = 0
# display screen resolution
SCREEN_SIZE = (1920, 1080)
# define the codec
fourcc = cv.VideoWriter_fourcc(*"XVID")
# create the video write object
out = cv.VideoWriter("output.mkv", fourcc, 25.0, (SCREEN_SIZE))

def count():
    print("Count function started!")
    while x == 0:
        # make a screenshot
        img = pyautogui.screenshot()
        frame = np.array(img)
        # convert colors from BGR to RGB
        frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
        # write the frame
        frames.append(frame)
        print("Frame added!")
        if y == 1:
            break

def increase_var():
    global z
    z += 1
    print(z)
    print(frames[0])

def release_video():
    if y == 1:
        print("Started processing frame data...")
        for i in frames:
            out.write(i)
            print("Loop functioning.")
        cv.destroyAllWindows()
        out.release()
        print("Count function proccessed.")

while True:
    if keyboard.is_pressed('r'):
        input("Start?")
        print("Both recording")
        if __name__ == "__main__":
            ctx = mp.get_context('spawn')
            p1 = ctx.Process(target = count)
            p1.start()
            while True:
                if keyboard.is_pressed('q'):
                    print("Did it!!!")
                    y += 1
                    print("y = " + str(y))
                    break
            input("Done?")
            increase_var()
            if z == 1:
                x = x + 1
                print("x was increased!")
        
        
    if x == 1:
        p1.terminate()
        p1.join()
        release_video()
        print("We're here!")
        input()
        x += 1

标签: python-multiprocessing

解决方案


推荐阅读