我正在做一些测试活动,这需要我捕获应用程序、数据库系统等的屏幕截图并将其保存到文档中。
整个活动截图超过50张。 Python 中有没有一种方法可以使用 Windows 快捷键(例如 Ctrl + Alt + Shift + C)进行屏幕截图并将图像附加到文档文件中?
我相信Python程序应该在后台运行,就像Unix中的nohup。
要使用热键将屏幕截图存储在Word中,您可以使用库的组合。
要使此脚本正常工作,您需要在运行脚本之前创建 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
相同的代码只需进行一些小的更改即可工作。 感谢您提供上面的代码。然而,面临一些挑战并解决了一些问题,下面的代码工作得很好。屏幕截图带有时间戳。
hotkey = 'win+prtscn' # use this combination anytime while script is running
shot = pyautogui.screenshot() # to take screenshot full screen with timestamp
docxfile = r'C:\tmp\shots.docx' # main document ADDED THIS STATEMENT
只有使用该代码添加或更改的上述语句才能完美运行。 也可以使用热键 Windows 徽标以及打印屏幕。当代码处于调试模式时
win+prntscrn
会将图像存储在代码中指定的位置以及默认位置图片截图文件夹中
停止调试模式后,win+prntscrn 将仅将图像存储在默认位置的屏幕截图文件夹中。
但是,在停止调试模式后使用热键
cntrl+shift+q
时,shot.png 图像将具有没有时间戳的图像。
在调试模式下,使用上述热键时 shot.png
将显示图像和时间戳。
创建新的空白文档:
except:
document = docx.Document()
#document.save('CKS1.docx')
document.save('C:/tmp/CKS0.docx')
print ('Doc created.') # Doc created
#doc1 = Document('CKS0.docx') # open document
#doc1.add_picture(shotfile, width=Inches(7)) # add image, 7 inches wide
#doc1.save('CKS0.docx') # update document
print ('Done capture.')
print("Previous file was corrupted or didn't exist - new file was created.")