You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何实现选中文本自动复制或循环执行Ctrl+C的Python程序?

Python Scripts for Auto-Copy on Text Selection or Continuous Ctrl+C Spam

Hey there! Let's build those two Python utilities you asked for. We'll use pyautogui for simulating keyboard inputs and pynput for listening to mouse/keyboard events—they're lightweight and get the job done perfectly for this kind of task.

First, install the required libraries:

pip install pyautogui pynput

Option 1: Auto-Copy When Text is Selected

This script listens for mouse selection actions (when you drag to highlight text) and automatically triggers Ctrl+C the moment you release the mouse button.

import pyautogui
from pynput.mouse import Listener

# Track mouse press position to distinguish clicks from selections
press_x, press_y = 0, 0

def on_press(x, y, button, pressed):
    global press_x, press_y
    if pressed:
        # Record where the mouse was first pressed
        press_x, press_y = x, y

def on_release(x, y, button, pressed):
    # Check if this was a selection (press and release positions don't match)
    if (x != press_x or y != press_y) and button.name == "left":
        # Simulate Ctrl+C to copy the selected text
        pyautogui.hotkey('ctrl', 'c')
        print("Selected text copied automatically!")

# Start the mouse listener and keep it running
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

Quick Notes:

  • This works for most standard text selection (drag-to-highlight) scenarios—won't trigger on single clicks or right-clicks.
  • For macOS users, replace 'ctrl' with 'command' in the hotkey call.
  • You might need to grant your Python interpreter access to control mouse/keyboard via system permissions if the script doesn't work initially.

Option 2: Continuous Ctrl+C Until Stopped

This script spams Ctrl+C in a loop. Press the Esc key anytime to stop it immediately.

import pyautogui
from pynput.keyboard import Listener, Key

# Flag to control the loop state
running = True

def on_press(key):
    global running
    # Stop the script when Esc is pressed
    if key == Key.esc:
        running = False
        print("Stopping Ctrl+C spam...")
        return False

# Start the keyboard listener in a background thread
listener = Listener(on_press=on_press)
listener.start()

# Loop to send Ctrl+C repeatedly
print("Starting continuous Ctrl+C. Press Esc to stop.")
while running:
    pyautogui.hotkey('ctrl', 'c')
    pyautogui.sleep(0.1)  # Adjust this delay to change spam speed (lower = faster)

# Wait for the listener to clean up
listener.join()

Quick Notes:

  • Tweak the sleep(0.1) value to adjust how often Ctrl+C is sent—lower numbers mean faster repetition.
  • Again, swap 'ctrl' with 'command' if you're on macOS.
  • Pro tip: Don't run this while you have unsaved work open—continuous Ctrl+C can interrupt active processes!

内容的提问来源于stack exchange,提问作者Fred_Alb

火山引擎 最新活动