Skip to main content
 首页 » 编程设计

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

2025年05月04日35daizhj

我想将我的试用开始时间打印到我的日志文件中。但是,我需要在 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”和时间 - 每次刷新都有一行。

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

请您参考如下方法:

这只是 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.