You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写脚本实现按下任意键盘按键时执行指定命令并循环?

How to Run a Command Every Time Any Key is Pressed (Cross-Platform Scripts)

Got it, let's tackle this problem—you want a script that triggers a specific command every time any keyboard key is pressed, and keeps running to listen for future key presses. I'll break this down by operating system since keyboard handling works differently across Linux, Windows, and macOS.

Linux Solutions

Option 1: Python Script (Global Key Listening)

This uses the keyboard library to listen for any key press system-wide (not just in the terminal window).

First, install the required library:

pip install keyboard

Then create the script (e.g., key_trigger.py):

import keyboard
import subprocess

def execute_command():
    # Replace this with your actual command
    custom_command = "echo 'Key pressed! Executing command...' >> key_log.txt"
    # Run the command
    subprocess.run(custom_command, shell=True, check=True)

# Attach the command to every key press
keyboard.on_press(lambda _: execute_command())

# Keep the script running to listen for keys
print("Listening for key presses... Press Ctrl+C to stop.")
keyboard.wait()
  • Notes:
    • Replace custom_command with whatever you need to run (e.g., sudo systemctl restart nginx or python your_script.py).
    • You might need to run this with sudo to get global key listening permissions on Linux.

Option 2: Bash Script (Terminal-Only Listening)

If you only need to listen for keys within the terminal window, no extra libraries are required:

#!/bin/bash

echo "Listening for key presses in this terminal... Press Ctrl+C to exit."

while true; do
    # Read a single key without echoing it
    read -n1 -s pressed_key
    # Replace this with your command
    echo "Key '$pressed_key' pressed at: $(date)" >> terminal_key_log.txt
done

Make it executable with chmod +x key_trigger.sh, then run it with ./key_trigger.sh.

Windows Solutions

Option 1: Python Script (Global Listening)

Same as Linux, use the keyboard library. Install it first with pip install keyboard, then use this script:

import keyboard
import subprocess

def run_custom_command():
    # Replace with your Windows command
    custom_command = "echo Key pressed! >> C:\\key_log.txt"
    subprocess.run(custom_command, shell=True, check=True)

keyboard.on_press(lambda _: run_custom_command())

print("Listening for key presses... Press Ctrl+C to stop.")
keyboard.wait()
  • Notes: Run the script as Administrator if you need to listen to keys outside the terminal.

Option 2: PowerShell Script (Terminal or Global)

No extra installs needed for this PowerShell approach:

Write-Host "Listening for key presses... Press Ctrl+C to exit."

while ($true) {
    # Read a key without displaying it
    $key = [Console]::ReadKey($true)
    # Replace with your command
    Write-Host "Key '$($key.Key)' pressed at: $(Get-Date)" | Out-File -Append C:\key_log.txt
}

Run this in PowerShell—if you want global listening, run PowerShell as Administrator.

macOS Solutions

Option 1: Python Script (Global Listening)

Use the keyboard library, but macOS requires extra permissions. First install it:

pip install keyboard

Then create the script and run it with sudo to get access to global key events:

import keyboard
import subprocess

def run_command():
    custom_command = "echo 'Key pressed!' >> ~/key_log.txt"
    subprocess.run(custom_command, shell=True, check=True)

keyboard.on_press(lambda _: run_command())

print("Listening for key presses... Press Ctrl+C to stop.")
keyboard.wait()

When you run sudo python3 key_trigger.py, you'll need to grant accessibility permissions to your terminal in System Settings > Privacy & Security > Accessibility.

Option 2: Bash Script (Terminal-Only)

For terminal-only key listening, use this simple bash loop:

#!/bin/bash

echo "Listening for key presses in this terminal... Press Ctrl+C to exit."

while true; do
    # Read a single key silently
    read -n1 -s key
    echo "Key '$key' pressed at: $(date)" >> ~/terminal_key_log.txt
done

Make it executable with chmod +x key_trigger.sh and run it.


内容的提问来源于stack exchange,提问作者Gabrijel Gabi Žuljević

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:28:03