【问题标题】:python waiting for input while running scriptpython在运行脚本时等待输入
【发布时间】:2016-05-03 22:12:48
【问题描述】:

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

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

【问题讨论】:

  • 嗯,它在一个单独的线程中。这不就是线程的想法吗?

标签: python loops input


【解决方案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()

【讨论】:

  • 感谢您的回复!在检查线程是否还活着之后,是否有办法“恢复”线程?否则这个方法只能在用户听到声音的情况下使用一次,对吧?
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2019-05-08
  • 2018-04-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多