程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The python recording screen widget has been debugged and run successfully

編輯:Python

Because the recent test needs to record the operation process of the system interface,Because it is a full screen operation,所以用pythonMake a simple screen recording widget.

The implementation process is also relatively simple,It is by taking continuous screenshots of screen operations,Finally, the screenshots are synthesized into a process of operating video.Since we are just doing a simple screenshot function,No audio effects were added.

1、准備

Before we start, let's introduce the third parties used in the pastpython模塊.

from PIL import ImageGrab
import numpy as np
import cv2
import datetime
from pynput import keyboard
import threading
from loguru import logger
import time

Because the implementation process is relatively small,Here we no longer create standard onesclass實現,直接在.pyFile write related functions to achieve.

2、代碼

The realization process is mainly realized through two functions,One is to implement specific screenshot operations,and write it to the video.The other is used to monitor keyboard input,If pressedescPress the key to exit the current recording operation.

Initialize a variable as a stop flag.

is_running = True

Create a recording process generator functiongenerate_video,Used to generate recorded video.

def generate_video():
''' Generate a record video function :return: '''
file_name = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')
screen = ImageGrab.grab()
width, height = screen.size
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video = cv2.VideoWriter('%s.avi' % file_name, fourcc, 20, (width, height))
for n in range(3):
logger.debug(str(3 - n) + '秒後開始錄制!')
time.sleep(1)
while True:
im1 = ImageGrab.grab()
im2 = cv2.cvtColor(np.array(im1), cv2.COLOR_RGB2BGR)
video.write(im2)
if is_running is False:
logger.debug('Screen recording has ended!')
break
video.release()

Create a keyboard listener functionpress_keyboard,監聽輸入,If pressedesckey to change the running state.

is_running=False
def press_keyboard(key):
''' Keyboard listener function :param key: :return: '''
global is_running
if key == keyboard.Key.esc:
logger.debug('ESC已經被按下,End recording now!')
is_running = False
return False

執行主函數main,Start to perform screen recording.

if __name__ == '__main__':
thread_ = threading.Thread(target=generate_video)
thread_.start()
logger.debug(' Start to enter video recording!')
with keyboard.Listener(on_press=press_keyboard) as listener:
listener.join()

最後,使用pyinstaller將其打包成exeexecutable application,When using it, double-click to open it to start the process of recording the screen.

pyinstaller -i .\video.ico -Fw .\test2.py

至此,Record Screen gadget and you're done.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved