繁体   English   中英

python在运行脚本时等待输入

[英]python waiting for input while running script

我正在尝试编写一种听力测试,它将以越来越大的音量播放声音,直到遍历其音量列表或用户输入内容为止,表明他们听到了声音。 为此,我试图让脚本在继续循环以增加音量的同时要求输入,但是通常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)

为了避免脚本过长,它引用了我在此处未定义的两个函数。

您的线程的几个问题。 创建线程并传递目标时,您正在执行

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

这正在调用该函数。 您应该像这样通过目标。

thread = threading.Thread(target = tone_stopper)

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

但是,您要做的只是查看用户是否在input提示下输入了任何内容。 在这种情况下,线程将终止。

因此,您应该简单地检查if not thread.is_alive()

这是一个完全无用的示例,仅显示用户单击Enter时线程终止。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM