如何检测特定URL被复制到剪贴板并触发脚本执行?
Got it, let's break down how to solve your two clipboard-related tasks: detecting specific content in copied text, and automatically running a script when a target URL hits your clipboard. Here's a practical, step-by-step approach that works across platforms:
We'll use Python for this—it's cross-platform, easy to tweak, and has great clipboard handling libraries. First, install the core dependency:
pip install pyperclip
For Windows, this works out of the box. For macOS, you'll need an extra package to access the system clipboard:
pip install pyobjc
For Linux, make sure you have xclip or xsel installed via your package manager (e.g., sudo apt install xclip for Debian/Ubuntu).
First, let's build the logic to check if copied text contains your target content. We'll add a loop to continuously monitor the clipboard, and skip duplicate checks to avoid redundant work.
Now we'll extend that logic to trigger your script as soon as the target URL is detected. Here's the full working code:
import pyperclip import time import subprocess # Configure these values to match your needs TARGET_URL = "https://your-target-url.com/" # Replace with your URL (or use a regex for flexibility) SCRIPT_PATH = "./your-script.sh" # Use full path if your script isn't in the same directory POLL_INTERVAL = 0.5 # How often to check the clipboard (in seconds) last_copied = "" def monitor_clipboard(): global last_copied current_content = pyperclip.paste() # Skip if the clipboard content hasn't changed if current_content == last_copied: return last_copied = current_content # Check if the copied text includes our target URL if TARGET_URL in current_content: print(f"✅ Detected target URL: {current_content}") print("Running your script...") # Execute the script (adjust shell=True based on your OS/script type) try: result = subprocess.run( SCRIPT_PATH, shell=True, check=True, capture_output=True, text=True ) print(f"Script output:\n{result.stdout}") except subprocess.CalledProcessError as e: print(f"❌ Script failed with error:\n{e.stderr}") if __name__ == "__main__": print(f"Listening for clipboard content containing '{TARGET_URL}'...") print("Press Ctrl+C to stop monitoring.") try: while True: monitor_clipboard() time.sleep(POLL_INTERVAL) except KeyboardInterrupt: print("\nStopped clipboard monitoring.")
Key Customizations:
- Regex Matching: If you need to match multiple similar URLs (e.g., any subdomain of
example.com), replace theTARGET_URL in current_contentcheck with a regex:import re if re.search(r"https://.*\.example\.com/", current_content): # Run script - Windows Scripts: For
.bator.exefiles, use a full path likeC:\\scripts\\my-script.bat(note the double backslashes). - Polling Interval: Adjust
POLL_INTERVALto balance responsiveness and resource usage—0.5 seconds is a good middle ground.
The above code uses polling, which is simple but uses a small amount of CPU. For a more efficient approach that listens directly for clipboard update events (no looping), here's a quick example for Windows using pywin32:
First install the dependency:
pip install pywin32
Then the code:
import win32api import win32clipboard import win32con import subprocess TARGET_URL = "https://your-target-url.com/" SCRIPT_PATH = "C:\\scripts\\my-script.bat" def handle_clipboard_update(): win32clipboard.OpenClipboard() try: if win32clipboard.IsClipboardFormatAvailable(win32con.CF_TEXT): content = win32clipboard.GetClipboardData(win32con.CF_TEXT).decode('utf-8') if TARGET_URL in content: print("Detected target URL—running script!") subprocess.run(SCRIPT_PATH, shell=True) finally: win32clipboard.CloseClipboard() return win32api.SetClipboardViewer(handle_clipboard_update) # Start the listener win32api.SetClipboardViewer(handle_clipboard_update) print("Listening for clipboard events...") print("Press Ctrl+C to stop.") try: win32api.PumpMessages() except KeyboardInterrupt: win32api.ChangeClipboardChain(win32api.GetClipboardViewer(), 0) print("\nStopped listening.")
For macOS or Linux, you'd use platform-specific APIs (like NSPasteboard for macOS or xlib for Linux), but the polling method is usually sufficient for most use cases.
内容的提问来源于stack exchange,提问作者Mohamed Allam Naeem

