我正在做一些测试事件,这需要我捕获应用程序、数据库系统等的屏幕截图并将其保存到文档中。
整个事件有超过50张截图。 Python中有没有一种方法可以使用Windows快捷键截取屏幕截图(例如,Ctrl + Alt + Shift + < kbd>C)并将图像附加到文档文件中?
我相信Python程序应该在后台运行,例如nohup在 Unix 中。
最佳答案
用于将屏幕截图存储在 Word 中使用热键,您可以使用库的组合。
- 使用win32gui打开Word
- 使用python-docx更新文档并保存
- 使用PyAutoGUI 进行屏幕捕获
- 使用键盘监听热键
要使该脚本正常工作,您需要在运行该脚本之前创建 Word 文档。
# Need these libraries
# pip install keyboard
# pip install PyAutoGUI
# pip install python-docx
# pip install win32gui
import keyboard
import pyautogui
from docx import Document
from docx.shared import Inches
import win32gui
from PIL import ImageGrab
shotfile = "C:/tmp/shot.png" # Temporary image storage
docxfile = "C:/tmp/shots.docx" # The main document
hotkey = 'ctrl+shift+q' # Use this combination anytime while the script is running
def do_cap():
try:
print ('Storing capture...')
hwnd = win32gui.GetForegroundWindow() # Active window
bbox = win32gui.GetWindowRect(hwnd) # Bounding rectangle
# capture screen
shot = pyautogui.screenshot(region=bbox) # Take a screenshot, active app
# shot = pyautogui.screenshot() # Take a screenshot full screen
shot.save(shotfile) # Save the screenshot
# Append to the document. Doc must exist.
doc = Document(docxfile) # Open the document
doc.add_picture(shotfile, width=Inches(7)) # Add the image, 7 inches wide
doc.save(docxfile) # Update the document
print ('Done capture.')
except Exception as e: # Allow the program to keep running
print("Capture Error:", e)
keyboard.add_hotkey(hotkey, do_cap) # Set hot keys
print("Started. Waiting for", hotkey)
keyboard.wait() # Block forever
关于python - 使用 Python 后台脚本捕获屏幕截图并保存到文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63315215/