在 psychopy 的 while 循环中只写出第一个结果

Write out only first result in while loop in psychopy

我想将我的试用开始时间打印到我的日志文件中。但是,我需要在 while(计时器)循环内写入日志文件,这意味着我在该循环中所做的任何事情都将在每次屏幕刷新时完成。

问题是我只想将第一个 clock.getTime() 调用的结果写入日志文件。如果我这样做:

while timer.getTime() >0: # while time isn't up (turns neg when time's up)
    for key in event.getKeys():
        if key in ['escape']:
            core.quit() # quit if they press escape

        timeText.draw(window)
        timeline.draw(window)
        cursorImage.draw(window)

        ## flip so it actually appears
        window.flip()
        OnsetTime = clock.getTime()
        logfile.write('OnsetTime, %s' % OnsetTime)

我的日志文件中有很多行显示 'OnsetTime' 和时间 - 每次刷新一个。

我只想打印第一个,但我不知道该怎么做。

我想你想要这样的东西:

while timer.getTime() >0: # while time isn't up (turns neg when time's up)
    first = True
    for key in event.getKeys():
        if key in ['escape']:
            core.quit() # quit if they press escape

        timeText.draw(window)
        timeline.draw(window)
        cursorImage.draw(window)

        ## flip so it actually appears
        window.flip()
        OnsetTime = clock.getTime()
        if first:
            logfile.write('OnsetTime, %s' % OnsetTime)
            first = False

但是,如果您只想要第一个,first = True 则必须在 While 循环之外。

这只是 CasualDemon 提议的另一种方法,但我认为它更优雅(三行代码用于日志记录,而不是 5 行):

def logOnsetTime():
    """Function which allows launching this code right after a window.flip()"""
    logfile.write('OnsetTime, %s' % clock.getTime())

window.callOnFlip(logOnsetTime)  # runs on first flip
while timer.getTime() >0: # while time isn't up (turns neg when time's up)
    for key in event.getKeys():
        if key in ['escape']:
            core.quit() # quit if they press escape

        timeText.draw(window)
        timeline.draw(window)
        cursorImage.draw(window)

        ## flip so it actually appears.
        window.flip()

如果您想要记录每个按键,请将 window.callOnFlip(logOnsetTime) 放在 while 循环中。还有一个专门用于日志记录的 window.logOnFlip 方法,但它只是将输入字符串保存到日志中,时间戳记为全局时钟,因此它不会保存你的 clock.[=14= 的时间]