如何实现Python脚本按下指定按键后自动重启自身
Got it, let's tackle this problem: you want your Python script to automatically restart itself from the beginning when you press the Q key. Here's a straightforward, cross-platform way to do it using common libraries and clean logic.
Step 1: Install Required Libraries
First, we'll use the keyboard library to detect real-time key presses (it works on Windows, macOS, and Linux). Install it via pip:
pip install keyboard
Note: On some systems, you might need to run your script with administrator/root privileges for the keyboard library to access input events properly.
Step 2: Core Logic Breakdown
- Key Detection: We'll set up a listener that watches for the Q key press. When detected, it triggers a restart.
- Restarting the Script: We'll use
os.execv()to replace the current process with a new instance of the script. This is cleaner than spawning a subprocess because it fully replaces the existing process, avoiding leftover threads or resources.
Step 3: Full Working Code
Here's a complete example with a sample script flow, key detection, and restart functionality:
import os import sys import keyboard def restart_script(): """Restart the current script from the start""" print("\nRestarting script...") # Replace the current process with a fresh instance of the script os.execv(sys.executable, ['python'] + sys.argv) def main(): print("Script is running! Press Q to restart, or Ctrl+C to exit.") # Set up a hotkey listener for the 'q' key keyboard.add_hotkey('q', restart_script) try: # Keep the script running to listen for key presses while True: # Replace this block with your actual script logic print("Doing ongoing work... (press Q to restart)") # Optional: Add a small delay to avoid spamming the console keyboard.wait('space') # Remove this line if you want continuous looping except KeyboardInterrupt: print("\nExiting script manually.") if __name__ == "__main__": main()
Alternative: Using pynput (If keyboard Has Permission Issues)
If you run into permission problems with keyboard, the pynput library is another reliable option. Install it first:
pip install pynput
Here's the equivalent code using pynput:
import os import sys from pynput.keyboard import Listener, Key def restart_script(): print("\nRestarting script...") os.execv(sys.executable, ['python'] + sys.argv) def on_press(key): try: # Check if the pressed key is 'q' if key.char == 'q': restart_script() except AttributeError: # Ignore special keys like Ctrl, Alt, etc. unless you need them pass def main(): print("Script is running! Press Q to restart, or Ctrl+C to exit.") # Start the key listener with Listener(on_press=on_press) as listener: try: while True: print("Doing ongoing work... (press Q to restart)") # Keep the main thread alive without spamming listener.join(1) except KeyboardInterrupt: print("\nExiting script manually.") listener.stop() if __name__ == "__main__": main()
Important Notes
- Permissions: Both libraries may require elevated privileges to access keyboard input. On Linux/macOS, run with
sudo; on Windows, launch Command Prompt as Administrator. - Cleanup: If your script uses resources like open files or network connections, add cleanup code before calling
restart_script()to avoid leaks. - Cross-Platform: Both examples work across Windows, macOS, and Linux—
sys.executableautomatically points to your Python interpreter path.
内容的提问来源于stack exchange,提问作者michal

