如何用Python实现触发式保存最近4秒输入内容至文本文件?
Sure thing! This is totally doable with Python—you just need to combine real-time input tracking, a rolling time-based buffer, and trigger condition checks. Let's walk through a practical implementation that covers your needs:
Core Components We'll Build
- A keystroke listener to capture every user input with timestamps
- A time-aware buffer that automatically drops inputs older than 4 seconds
- Trigger detectors for your specified conditions (we'll use repeated keys and CPU load as examples)
- A function to save the recent 4-second input log to a text file
Step 1: Install Dependencies
First, install the libraries we'll use for input capture and system monitoring:
pip install pynput psutil
Step 2: Full Implementation Code
This script will run in the background, track inputs, and save the log when your trigger conditions are met:
import time from pynput import keyboard from collections import deque import psutil # Initialize a deque to store keystrokes with their timestamps keystroke_buffer = deque() def on_press(key): """Callback function to handle every keystroke press""" try: # Record alphanumeric keys as their character keystroke_buffer.append((time.time(), key.char)) except AttributeError: # Record special keys (space, enter, backspace, etc.) as their string representation keystroke_buffer.append((time.time(), str(key))) def prune_old_keystrokes(): """Remove any keystrokes from the buffer that are older than 4 seconds""" current_time = time.time() while keystroke_buffer and (current_time - keystroke_buffer[0][0]) > 4: keystroke_buffer.popleft() def check_triggers(): """Check if any of our trigger conditions are met""" current_time = time.time() # Trigger 1: 'a' key pressed 5+ times in the last 1 second a_press_count = sum(1 for ts, key in keystroke_buffer if (current_time - ts) <= 1 and key == 'a') if a_press_count >= 5: print("Trigger activated: 'a' pressed 5 times!") return True # Trigger 2: CPU usage exceeds 80% (simulates frame drop/performance hit) cpu_usage = psutil.cpu_percent(interval=0.1) if cpu_usage > 80: print(f"Trigger activated: CPU usage at {cpu_usage}%!") return True # Add your custom triggers here (e.g., frame rate checks with pygame/opencv) return False def save_recent_inputs(): """Save the last 4 seconds of inputs to a text file""" prune_old_keystrokes() # Ensure we only keep valid 4-second window with open("recent_input_log.txt", "w", encoding="utf-8") as log_file: log_file.write("=== Last 4 Seconds of User Input ===\n") for timestamp, key in keystroke_buffer: time_since_press = round(time.time() - timestamp, 2) log_file.write(f"{time_since_press}s ago: {key}\n") print("Saved recent inputs to recent_input_log.txt") def main(): # Start the keyboard listener in a background thread listener = keyboard.Listener(on_press=on_press) listener.start() print("Listening for inputs... Press Ctrl+C to exit.") try: while True: prune_old_keystrokes() if check_triggers(): save_recent_inputs() # Optional: Clear buffer and add cooldown to avoid duplicate saves keystroke_buffer.clear() time.sleep(2) time.sleep(0.1) # Reduce unnecessary CPU usage except KeyboardInterrupt: print("\nExiting program...") listener.stop() if __name__ == "__main__": main()
Customization Tips
- Add mouse input tracking: Use
pynput.mouseto capture clicks/movements, just like we did with keyboard inputs. - Frame rate trigger: If you're monitoring frame drops in a game/app, use libraries like
pygameorOpenCVto fetch real-time frame rates and add a check incheck_triggers(). - Adjust buffer window: Change the
4inprune_old_keystrokes()to modify how much recent input you want to save. - Custom triggers: Add logic for other conditions (e.g., specific key combinations, system memory usage) in the
check_triggers()function.
Notes
- On Windows, you may need to run the script as an administrator for the keyboard listener to work properly.
- The
pynputlibrary works across Windows, macOS, and Linux, but special key names might vary slightly between systems.
内容的提问来源于stack exchange,提问作者Charlie
相关产品推荐
相关产品推荐

