1

I am trying to simulate ctrl+c keyboard event in the python3 using the library pyautogui. Unfortunately, the library doesn't generate this event. Is there any other way to generate this?

The following code is not working,

from pyautogui import hotkey

hotkey('ctrl', 'c')

I want to do this task for the following code. The code can record live audio for the arbitrary duration and the recording can stop anytime by pressing 'Ctrl+c'. I want to generate this event so that I can add some additional features.

import os
import sys
import time
import queue
import soundfile as f
import sounddevice as sd

def callback(indata, frames, time, status):
            """
    This function is called for each audio block from the record function.
    """

    if status:
        print(status, file=sys.stderr)
    q.put(indata.copy())

def record(filename):

    try:
        # Make sure the file is open before recording begins
        with sf.SoundFile(filename, mode='x', samplerate=48000, channels=2, subtype="PCM_16") as file:
            with sd.InputStream(samplerate=48000, channels=2, callback=callback):
                print('START')
                print('#' * 80)
                """ 
                Here is the place I want to generate the event (Ctrl+c) 
                after n minutes
                """
                print('press Ctrl+c to stop the recording')
                while True:
                    file.write(q.get())
    except KeyboardInterrupt:
        print('The recording is over.')

if __name__ == "__main__":
    q = queue.Queue()
    record('filename.wav')

1 Answers1

0

This is just a suggestion and may not be good, because I'm very beginner in python.

Use PyWin32 to call windows API GenerateConsoleCtrlEvent(). You can generate CTRL+C with this API, so it may solve your problem if you call it with PyWin32.

Update:

Here is my first ever python code. You can use send_ctrl_c function to send CTRL-C to another process. I checked it and it works.

import win32api as api
import win32console as con

# takes another process id as argument. method sleeps for 2 seconds 
def send_ctrl_c(pid) :
 con.FreeConsole()
 if con.AttachConsole(int(pid)) == None : 
  api.SetConsoleCtrlHandler(None, 1)
  api.GenerateConsoleCtrlEvent(con.CTRL_C_EVENT, 0)
  api.Sleep(2000)
  con.FreeConsole()
  api.SetConsoleCtrlHandler(None, 0)

This code is written based on here and here.

Afshin
  • 8,839
  • 1
  • 18
  • 53
  • In my case it is not working. I will try to explain you clearly. I have a script which records the audio in a live way. The user can stop the recording by pressing Ctrl+c. I want to generate the Ctrl+c for this case so that the user cannot record more n minutes. I edited the question with the code. Please check it. –  Nov 15 '18 at 14:26