simulate ctrl+c event in windows 10 using python












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')









share|improve this question





























    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')









    share|improve this question



























      1












      1








      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')









      share|improve this question
















      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')






      python-3.x keyboard-events pyautogui






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 14:34







      M. Denis

















      asked Nov 14 '18 at 17:25









      M. DenisM. Denis

      528




      528
























          1 Answer
          1






          active

          oldest

          votes


















          1














          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.






          share|improve this answer


























          • I tried it. It doesn't work :(

            – M. Denis
            Nov 15 '18 at 7:32











          • @M.Denis updated reply with a working python code.

            – Afshin
            Nov 15 '18 at 12:44













          • 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.

            – M. Denis
            Nov 15 '18 at 14:26













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305694%2fsimulate-ctrlc-event-in-windows-10-using-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          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.






          share|improve this answer


























          • I tried it. It doesn't work :(

            – M. Denis
            Nov 15 '18 at 7:32











          • @M.Denis updated reply with a working python code.

            – Afshin
            Nov 15 '18 at 12:44













          • 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.

            – M. Denis
            Nov 15 '18 at 14:26


















          1














          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.






          share|improve this answer


























          • I tried it. It doesn't work :(

            – M. Denis
            Nov 15 '18 at 7:32











          • @M.Denis updated reply with a working python code.

            – Afshin
            Nov 15 '18 at 12:44













          • 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.

            – M. Denis
            Nov 15 '18 at 14:26
















          1












          1








          1







          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.






          share|improve this answer















          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 15 '18 at 12:44

























          answered Nov 14 '18 at 17:33









          AfshinAfshin

          3,0361625




          3,0361625













          • I tried it. It doesn't work :(

            – M. Denis
            Nov 15 '18 at 7:32











          • @M.Denis updated reply with a working python code.

            – Afshin
            Nov 15 '18 at 12:44













          • 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.

            – M. Denis
            Nov 15 '18 at 14:26





















          • I tried it. It doesn't work :(

            – M. Denis
            Nov 15 '18 at 7:32











          • @M.Denis updated reply with a working python code.

            – Afshin
            Nov 15 '18 at 12:44













          • 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.

            – M. Denis
            Nov 15 '18 at 14:26



















          I tried it. It doesn't work :(

          – M. Denis
          Nov 15 '18 at 7:32





          I tried it. It doesn't work :(

          – M. Denis
          Nov 15 '18 at 7:32













          @M.Denis updated reply with a working python code.

          – Afshin
          Nov 15 '18 at 12:44







          @M.Denis updated reply with a working python code.

          – Afshin
          Nov 15 '18 at 12:44















          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.

          – M. Denis
          Nov 15 '18 at 14:26







          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.

          – M. Denis
          Nov 15 '18 at 14:26






















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305694%2fsimulate-ctrlc-event-in-windows-10-using-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python