Console Control

0.1.0 · maintenance · verified Tue Apr 14

The `console-ctrl` library provides a simple mechanism to send a CTRL-C event to a target console process on Windows without triggering a `KeyboardInterrupt` in the calling Python process. It is currently at version 0.1.0, with its sole release in February 2021, indicating a low and likely inactive release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to start a separate Python process in a new console and then use `console-ctrl.send_ctrl_c()` to send a CTRL-C event to it, causing the target process to handle the `KeyboardInterrupt` while the calling script continues uninterrupted. This example is Windows-specific.

import subprocess
import time
import sys

# Only run on Windows, as this library is Windows-specific
if sys.platform == 'win32':
    from console_ctrl import send_ctrl_c

    print("Starting a dummy process...")
    # Start a simple Python script that prints every second
    # and can be terminated by CTRL-C
    dummy_script = """
import time
import sys
try:
    while True:
        print('Dummy process running...', flush=True)
        time.sleep(1)
except KeyboardInterrupt:
    print('\nDummy process caught CTRL-C and exiting.', flush=True)
sys.exit(0)
"""

    # Use subprocess.Popen to start the dummy process in a new console
    # CREATE_NEW_CONSOLE ensures it gets its own console, which is key for send_ctrl_c
    process = subprocess.Popen(
        [sys.executable, '-c', dummy_script],
        creationflags=subprocess.CREATE_NEW_CONSOLE
    )

    print(f"Dummy process started with PID: {process.pid}")
    time.sleep(3) # Let it run for a few seconds

    print(f"Sending CTRL-C to process {process.pid}...")
    send_ctrl_c(process.pid)

    try:
        # Wait for the process to terminate, with a timeout
        return_code = process.wait(timeout=5)
        print(f"Process terminated with return code: {return_code}")
    except subprocess.TimeoutExpired:
        print("Process did not terminate after sending CTRL-C. Terminating forcefully.")
        process.terminate()
        process.wait()

    print("Quickstart complete.")
elif sys.platform == 'linux' or sys.platform == 'darwin':
    print("This library is designed for Windows and will not work on Linux/macOS.")
    print("The quickstart example will not run on this platform.")
else:
    print("Unsupported operating system for this library.")

view raw JSON →