Python中的线程不会占用键盘中断

时间:2018-09-24 08:10:06

标签: python multithreading keyboardinterrupt

我是Threading的新手,我正在编写一个可以同时完成两个任务的简单程序。一个功能将录制任意时间的音频,而另一个功能将仅打印一些消息。在录制功能中,Ctrl + C键盘中断用于停止录制。但是,如果我将此函数放入python线程中,则Ctrl + C无法正常工作,并且无法停止记录。代码如下。任何帮助表示感谢。

import argparse
import tempfile
import queue
import sys
import threading
import soundfile as sf
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='sample_audio.wav'):
    """
    Audio recording.
    Args:
        filename (str): Name of the audio file
    Returns:
        Saves the recorded audio as a wav file
    """
    q = queue.Queue()
    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)
                print('press Ctrl+C to stop the recording')
                print('#' * 80)
                while True:
                    file.write(q.get())
    except OSError:
        print('The file to be recorded already exists.')
        sys.exit(1)
    except KeyboardInterrupt:
        print('The utterance is recorded.')

def sample():
    for i in range(10):
        print('---------------------------------------------------')

def main():
    # Threading
    thread_1 = threading.Thread(target=record, daemon=True)
    thread_2 = threading.Thread(target=sample, daemon=True)
    thread_1.start()
    thread_2.start()
    thread_1.join()
    thread_2.join()

if __name__ == "__main__":
    main()

0 个答案:

没有答案