Python 使用多线程时如何停止循环?
我正在学习如何在python中使用多线程,我有两个同时运行的函数(一个用鼠标和键盘重放一些输入,第二个记录过程),我希望第二个函数记录,直到没有更多的输入,因此,我将一个全局变量声明为false,并在不再有输入时将其更改为true,但while循环似乎不会接受变量的更改。这是我的代码:Python 使用多线程时如何停止循环?,python,Python,我正在学习如何在python中使用多线程,我有两个同时运行的函数(一个用鼠标和键盘重放一些输入,第二个记录过程),我希望第二个函数记录,直到没有更多的输入,因此,我将一个全局变量声明为false,并在不再有输入时将其更改为true,但while循环似乎不会接受变量的更改。这是我的代码: STOP_RECORDING = False file = "actions_test_10-07-2020_15-56-43.json" def main(): t1 = thre
STOP_RECORDING = False
file = "actions_test_10-07-2020_15-56-43.json"
def main():
t1 = threading.Thread(target=playActions, args=[file])
t2 = threading.Thread(target=recordScreen)
t1.start()
t2.start()
t1.join()
t2.join()
print("Done")
def recordScreen():
output = "video.avi"
img = pyautogui.screenshot()
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
# get info from img
height, width, channels = img.shape
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output, fourcc, 30.0, (width, height))
while not STOP_RECORDING:
try:
img = pyautogui.screenshot()
image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
out.write(image)
StopIteration(0.5)
except KeyboardInterrupt:
break
out.release()
cv2.destroyAllWindows()
def playActions(filename):
# basically repeats some inputs recorded before
STOP_RECORDING = True
可能最常用的方法是使用线程安全对象,如
队列
,并以这种方式传输数据。例如,我同意DJSchaffner的观点,但你也应该阅读和了解作用域和名称空间感谢你们两位我已经更好地理解了它的工作原理和代码现在正在工作