[英]simulate ctrl+c event in windows 10 using python
I am trying to simulate ctrl+c keyboard event in the python3 using the library pyautogui. 我正在尝试使用库pyautogui在python3中模拟ctrl + c键盘事件。 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'.
该代码可以在任意持续时间内录制现场音频,并且可以通过按“ 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')
This is just a suggestion and may not be good, because I'm very beginner in python. 这只是一个建议,可能并不好,因为我是python的初学者。
Use PyWin32 to call windows API GenerateConsoleCtrlEvent()
. 使用PyWin32调用Windows API
GenerateConsoleCtrlEvent()
。 You can generate CTRL+C with this API, so it may solve your problem if you call it with PyWin32
. 您可以使用此API生成CTRL + C,因此如果您使用
PyWin32
调用它可以解决您的问题。
Update: 更新:
Here is my first ever python code. 这是我的第一个python代码。 You can use
send_ctrl_c
function to send CTRL-C to another process. 您可以使用
send_ctrl_c
函数将CTRL-C发送到另一个进程。 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 . 此代码是根据此处和此处编写的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.