【问题标题】:simulate ctrl+c event in windows 10 using python使用 python 在 Windows 10 中模拟 ctrl+c 事件
【发布时间】:2018-11-15 22:34:53
【问题描述】:

我正在尝试使用库 pyautogui 在 python3 中模拟 ctrl+c 键盘事件。不幸的是,该库不会生成此事件。有没有其他方法可以生成这个?

以下代码不起作用,

from pyautogui import hotkey

hotkey('ctrl', 'c')

我想为以下代码执行此任务。该代码可以录制任意持续时间的实时音频,并且可以通过按“Ctrl+c”随时停止录制。我想生成这个事件,以便我可以添加一些额外的功能。

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


    【解决方案1】:

    这只是一个建议,可能不太好,因为我是python的初学者。

    使用PyWin32 调用windows API GenerateConsoleCtrlEvent()。您可以使用此 API 生成 CTRL+C,因此如果您使用 PyWin32 调用它可能会解决您的问题。

    更新:

    这是我的第一个 python 代码。您可以使用send_ctrl_c 函数将 CTRL-C 发送到另一个进程。我检查了它,它可以工作。

    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)
    

    这段代码是基于herehere编写的。

    【讨论】:

    • 在我的情况下它不起作用。我会尽力向你解释清楚。我有一个以现场方式录制音频的脚本。用户可以通过按 Ctrl+c 来停止录制。我想为这种情况生成 Ctrl+c 以便用户不能记录更多的 n 分钟。我用代码编辑了这个问题。请检查一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 2011-10-05
    • 1970-01-01
    • 2013-01-01
    相关资源
    最近更新 更多