python在运行脚本时等待输入

时间:2016-05-03 22:12:49

标签: python loops input

我正在尝试编写一个听力测试,它将以越来越大的声音播放声音,直到它遍历其音量列表或者有来自用户的输入,表明他们听到了声音。 要做到这一点,我试图让脚本在仍然循环以增加音量的同时请求输入,但通常input()将停止脚本。在第一次循环之后,线程似乎停止工作。这是我到目前为止所提出的:

def tone_stopper():
    """This function will take as input a pressed key on the keyboard and give
    True as output"""
    test = input("Press enter when you hear a tone: ")
    if test == " ":
        return True


def call_play_file(frequency, vol_list):
    """This function will play a frequency and stop when the user presses
    a button or stop when it reaches the loudest volume for a frequency,
    it takes as an input a frequency and a list of volumes
    and returns the loudness at which the sound was playing when a button was
    pressed"""
    for volume in vol_list: #plays a tone and then repeats it a different vol
        tone_generator(frequency, volume)
        play_file('hearingtest.wav')
        if thread == True:
            return frequency, volume

    return frequency, "didn't hear" #in case no button is pressed

thread = threading.Thread(target = tone_stopper())
thread.setDaemon(True)
thread.start()
vol_list = [4, 8, 12];
freq_left_right = random_freq_list(200, 18000, 500)
startplaying = call_play_file(freq_left_right, vol_list)

为了防止脚本过长,它引用了我在这里没有定义的两个函数。

1 个答案:

答案 0 :(得分:1)

你的线程几乎没有问题。在创建线程并传递目标时,您正在进行

thread = threading.Thread(target = tone_stopper())

这是调用该函数。你应该像这样传递目标。

thread = threading.Thread(target = tone_stopper)

您还在检查if thread == True。如果要检查线程是否存活,则应检查thread.is_alive()

但是,你想要的只是看看用户是否输入了input提示符。在这种情况下,线程将终止。

因此,您只需检查if not thread.is_alive()

即可

这是一个完全无用的示例,只是显示当用户点击进入时线程终止。

import threading

def test_thread():

    input("Press enter when you hear the sound.")

def test_func():

    while thread.is_alive():
        pass

    print("Thread is over. User heard a sound.")

thread = threading.Thread(target=test_thread)
thread.daemon = True
thread.start()
test_func()
相关问题