In our daily work, we often encounter situations where we need to perform a large number of repetitive tasks. For example, we often need to create files, enter content, save files, etc. Python provides a powerful automation library that can help us automate these tedious tasks. In this article, I will teach you how to use Python to simulate operating notepad, automatically enter text and save it to your desktop.
Goal: Automate the creation and saving of notepad files
We will write a Python script with the following steps:
- Launch Notepad app: Automatically open Notepad and hide the window.
- Enter text: Automatically copy a piece of text to the clipboard and paste it into Notepad.
- Save file: Automatically save text files to the desktop and automatically name the file.
- By simulating mouse clicks and keyboard input, we are able to implement these automated tasks in Python.
Implementation steps
First, you need to make sure that the following Python libraries are installed:
- pyautogui: used to simulate keyboard and mouse operations.
- win32con and win32gui: Used to operate Windows windows.
- win32clipboard: Used to operate the clipboard.
- os and time: used for system operation and time control.
If you have not installed these libraries, you can install them through the following command:
pip install pyautogui pywin32
Next, we can start writing code.
Note: There are some unnecessary steps in the code, which aim to demonstrate the ability of python to operate windows. For example, set the size and position of Notepad window, hide/show window, etc.
1. Import the necessary libraries
import os import time import win32con import win32gui import pyautogui import win32clipboard
os: Provides functions to interact with the operating system, such as running system commands, processing file paths, etc.
time: Used to set the delay in code execution to ensure that the simulation operation has enough time to complete.
win32con and win32gui: The interface for Windows GUI operation, used to operate windows, simulate keys, etc.
pyautogui: used to simulate keyboard and mouse operations, simulate clicks, inputs, keys, etc.
win32clipboard: Used to operate the clipboard, which can read or write the contents of the clipboard.
2. Functions that write to the clipboard
def write_to_clipboard(text): () () # Clear the clipboard (text) # Set the clipboard content ()
The function of this function is to write text to the clipboard. The specific steps are as follows:
- (): Open the clipboard for operation.
- (): Clear the content in the clipboard to prevent old content from being interfered with.
- (text): Set the incoming text to clipboard content.
- (): Close the clipboard after the operation is completed.
The key to this function is the clipboard operation, which allows you to insert text into other applications via simulated paste (Ctrl+V) without direct input.
3. Close Notepad and restart
('taskkill /im /f') ('notepad') (1) # Wait for Notepad to fully start
('taskkill /im /f'): Force shutdown of the Notepad process through system commands. taskkill is a command line tool for Windows. /im specifies the process name and /f forces the process to end. If Notepad is running, it will be turned off.
('notepad'): Launch a new Notepad app. startfile() is a function provided by Python's os module and can be used to start a program.
(1): Wait for 1 second to ensure that Notepad starts complete. The delay here is to give the Notepad window enough time to fully load, avoiding subsequent operations when the window is not fully loaded.
4. Get the window handle
hwnd = (None, 'Unt title - Notepad') print(hwnd) # Print window handle for debugging
(None, 'Unt Title - Notepad'): Find window handle (hwnd) by window title. None means not searching based on class name, only searching based on window title. 'Unt title - Notepad' is the default title for Notepad.
hwnd is the unique identifier of the window. It is an integer that can be used to further operate on the window.
5. Hide the window
(hwnd, win32con.SW_HIDE) (1)
(hwnd, win32con.SW_HIDE): This command hides the Notepad window. hwnd is the handle of the window, and win32con.SW_HIDE is the constant of the hidden window.
(1): Wait for 1 second to make sure the window has been successfully hidden.
6. Set the text content to be pasted
text = """ Free solicitation | Automation requirements Still having a headache for repetitive work? Data processing takes too long? We are soliciting automation requirements for free, whether it is file sorting, report generation, email processing or web crawling. As long as you have a need, I am willing to write scripts for you for free so that tedious tasks can be completed in one click! What can we do for you? File processing: batch renaming, classification archiving, data cleaning. Data processing: Excel automation, report generation, cross-platform synchronization. Web page crawling: Automatically obtain product information, market data or article content. Email management: Automatically send emails, download attachments, and classify archives. Daily tasks: Automatically schedule, remind tasks, and synchronize to project management tools. Other needs: We are willing to try it as long as you think of it! """
This is the text content we want to insert into notepad, which contains detailed information about the request collection. The text can be modified at will and will be changed according to your actual needs.
7. Write text to the clipboard
write_to_clipboard(text)
Call the write_to_clipboard() function we just defined to write the text content to the clipboard. After that, we can insert these contents into notepad through the paste operation.
8. Display the window and adjust the position
(hwnd, win32con.SW_SHOW) # Show window(1) (hwnd, 100, 100, 800, 600, True) # Resize and position the window
(hwnd, win32con.SW_SHOW): Show the hidden window.
(1): Wait for 1 second, make sure the window is displayed before performing subsequent operations.
(hwnd, 100, 100, 800, 600, True): Adjust the window position to (100, 100) and set the window size to 800x600 pixels. The True parameter here means force movement of the window.
9. Paste the text content and save the file
('ctrl', 'v') # ctrl + v (2)
('ctrl', 'v'): Simulate pressing Ctrl + V to paste the text from the clipboard into Notepad. pyautogui is a very powerful library that can simulate inputs such as keyboard, mouse, etc.
(2): Wait for 2 seconds to make sure the text is completely pasted to Notepad.
10. Save the file to the desktop
desktop_path = (("~"), r"Desktop\Demand Call.txt") ('ctrl', 's') (2) write_to_clipboard(desktop_path) ('ctrl', 'v') ('enter')
desktop_path = (("~"), r"Desktop\Requirement Solicitation Order.txt"): Construct the path to save the file, ("~") Get the current user's home directory, and then splice the path to the desktop.
('ctrl', 's'): Simulate pressing Ctrl + S keys to trigger the operation of saving the file.
(2): Wait for 2 seconds to make sure the save dialog box pops up.
write_to_clipboard(desktop_path): Write the file save path to the clipboard.
('ctrl', 'v'): Paste the path into the file name box.
('enter'): Press Enter to save the file.
11. Show prompt for successful saving
(desktop_path, title='File saved')
Use () to pop up a prompt box to notify the user that the file has been successfully saved to the desktop.
Summarize
Through the above code, we can simulate operating notepad, automatically enter text and save files to the desktop. Through Python's automation libraries pyautogui, win32gui, and win32clipboard, we can easily control Windows applications and perform text processing, which is very useful for some repetitive tasks.
The above is the detailed explanation of using Python to simulate the operation of Windows application windows. For more information about Python to simulate the operation of Windows windows, please pay attention to my other related articles!