本文整理汇总了Python中psychopy.logging.flush函数的典型用法代码示例。如果您正苦于以下问题:Python flush函数的具体用法?Python flush怎么用?Python flush使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了flush函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: doIdleTasks
def doIdleTasks(app=None):
global currentTask
if currentTask and currentTask['thread'] and \
currentTask['thread'].is_alive():
# is currently tunning in a thread
return 0
for taskName in tasks:
thisTask = tasks[taskName]
thisStatus = tasks[taskName]['status']
if thisStatus == NOT_STARTED:
currentTask = thisTask
currentTask['tStart'] = time.time() - _t0
currentTask['status'] = STARTED
logging.debug('Started {} at {}'.format(taskName,
currentTask['tStart']))
_doTask(taskName, app)
return 0 # something is in motion
elif thisStatus == STARTED:
if not currentTask['thread'] \
or not currentTask['thread'].is_alive():
# task finished so take note and pick another
currentTask['status'] = FINISHED
currentTask['thread'] = None
currentTask['tEnd'] = time.time() - _t0
logging.debug('Finished {} at {}'.format(taskName,
currentTask['tEnd']))
currentTask = None
continue
else:
return 0
logging.flush()
return 1
示例2: RunSequence
def RunSequence( sequence ):
#setup rules
global rules
global currentRule
global ruleList; ruleList = [] #a list of tuples containing the sequence of sorting rules (0, 1, 2, 3) and required n of correct repeats per set(5, 6, 7)
for item in sequence['blocks']:
ruleList.append( (int(item['rule']), int(item['reps'])) )
print 'RULELIST:', ruleList
global RULE_COUNT; RULE_COUNT = len( ruleList )
global ruleCount, cardCount, rightAnswers;
ruleCount = 0;
ShowInstruction( u'Aloita painamalla jotain näppäintä', -1 )
while ruleCount < RULE_COUNT:
currentRule = rules[ruleList[ruleCount][0]]
SetupTrial()
NextTrial( taskType )
answer = GetResponse()
if answer == 0: #ESC
break
else:
GiveFeedback( taskType, answer )
#if enough right answers given, update rule
if answer > 0:
if rightAnswers % ruleRepeats == 0: # rightAnswers can't be 0 here since retVal wouldn't be > 0
ruleCount += 1
rightAnswers = 0
logging.flush() #now with every rule change!
cardCount +=1
示例3: getEvents
def getEvents(self, timeout=10):
"""Look for a string that matches SDAT;\n.........EDAT;\n
and process it as events
"""
foundDataStart=False
t0=time.time()
while not foundDataStart and (time.time()-t0)<timeout:
if self.com.readline().startswith('SDAT'):
foundDataStart=True
logging.info("BBTK.getEvents() found data. Processing...")
logging.flush() #we aren't in a time-critical period so flush messages
break
#check if we're processing data
if not foundDataStart:
logging.warning("BBTK.getEvents() found no data (SDAT was not found on serial port inputs")
return []
#helper function to parse time and event code
def parseEventsLine(line, lastState=None):
"""Returns a list of dictionaries, one for each change detected in the state
"""
state = line[:12]
timeSecs = int(line[-14:-2])/10.0**6
evts=[]
evt=''
if lastState is None:
evts.append({'evt':'', 'state':state, 'time':timeSecs})
else:
for n in evtChannels.keys():
if state[n]!=lastState[n]:
if state[n]=='1':
evt = evtChannels[n]+"_on"
else:
evt = evtChannels[n]+"_off"
evts.append({'evt':evt, 'state':state, 'time':timeSecs})
return evts
#we've been sent data so work through it
events=[]
eventLines=[]
lastState=None
#try to read from port
self.pause()
self.com.setTimeout(2.0)
nEvents = int(self.com.readline()[:-2]) #last two chars are ;\n
self.com.readline()[:-2] # microseconds recorded (ignore)
self.com.readline()[:-2] #samples recorded (ignore)
while True:
line = self.com.readline()
if line.startswith('EDAT'): #end of data stream
break
events.extend(parseEventsLine(line, lastState))
lastState = events[-1]['state']
eventLines.append(line)
if nEvents != len(eventLines):
logging.warning("BBTK reported %i events but told us to expect %i events!!" %(len(events), nEvents))
logging.flush() #we aren't in a time-critical period so flush messages
return events
示例4: finish_sync
def finish_sync(self):
"""Rebuilds index and saves project file when the sync has finished
"""
proj = self.proj()
# when local/remote updates are complete refresh index based on local
proj.local.rebuild_index()
proj.index = proj.local.index
self._set_empty()
proj.save()
if hasattr(logging, 'flush'): # psychopy.logging has control of flush
logging.flush()
示例5: _warnTesting
def _warnTesting(self):
msg = "We need to run some tests on your graphics card (hopefully just once). " + \
"The BitsSharp will go into status mode while this is done. " + \
"It can take a minute or two."
logging.warn(msg)
logging.flush()
msgOnScreen = visual.TextStim(self.win, msg)
msgOnScreen.draw()
self.win.flip()
core.wait(1.0)
self.win.flip()
示例6: quit
def quit():
"""Close everything and exit nicely (ending the experiment)
"""
#pygame.quit() #safe even if pygame was never initialised
logging.flush()
for thisThread in threading.enumerate():
if hasattr(thisThread,'stop') and hasattr(thisThread,'running'):
#this is one of our event threads - kill it and wait for success
thisThread.stop()
while thisThread.running==0:
pass#wait until it has properly finished polling
sys.exit(0)#quits the python session entirely
示例7: shut_down_cleanly
def shut_down_cleanly(subdata,win):
"""
shut down experiment and try to save data
"""
win.close()
logging.flush()
try:
f=open('Output/%s_%s_subdata.pkl'%(subdata['subcode'],subdata['datestamp']),'wb')
pickle.dump(subdata,f)
f.close()
except:
pass
示例8: sendMessage
def sendMessage(self, message, autoLog=True):
"""Send a command to the device (does not wait for a reply or sleep())
"""
if self.com.inWaiting():
inStr = self.com.read(self.com.inWaiting())
logging.warning("Sending '%s' to %s but found '%s' on the input buffer" %(message, self.name, inStr))
if not message.endswith(self.eol):
message += self.eol #append a newline if necess
self.com.write(message)
self.com.flush()
if autoLog:
logging.debug('Sent %s message:' %(self.name) +message.replace(self.eol, ''))#send complete message
logging.flush() #we aren't in a time-critical period so flush messages
示例9: throw_ball
def throw_ball(fromP, toP):
global trialCnt, holder, rndCnt
key = "%ito%i" % (fromP,toP)
logging.log(level=logging.DATA, msg="round %i - trial %i - throw: %s - %s" % (round, trialCnt, key, condition))
for s in throw[key]:
players.setImage('images/%s/%s' % (key,s))
players.draw()
win.flip()
core.wait(0.15)
trialCnt+=1
rndCnt+=1
holder=toP
logging.flush()
select_throw()
示例10: sendMessage
def sendMessage(self, message, autoLog=True):
"""Send a command to the device (does not wait for a reply or sleep())
"""
if self.com.inWaiting():
inStr = self.com.read(self.com.inWaiting())
msg = "Sending '%s' to %s but found '%s' on the input buffer"
logging.warning(msg % (message, self.name, inStr))
if type(message) is not bytes:
message = bytes(message, 'utf-8')
if not message.endswith(self.eol):
message += self.eol # append a newline if necess
self.com.write(message)
self.com.flush()
if autoLog:
msg = b'Sent %s message:' % (self.name)
logging.debug(msg + message.replace(self.eol, b'')) # complete msg
# we aren't in a time-critical period so flush msg
logging.flush()
示例11: quit
def quit():
"""Close everything and exit nicely (ending the experiment)
"""
#pygame.quit() #safe even if pygame was never initialised
logging.flush()
for thisThread in threading.enumerate():
if hasattr(thisThread,'stop') and hasattr(thisThread,'running'):
#this is one of our event threads - kill it and wait for success
thisThread.stop()
while thisThread.running==0:
pass#wait until it has properly finished polling
# could check serverCreated() serverBooted() but then need to import pyo
# checking serverCreated() does not tell you whether it was shutdown or not
for ps in pyoServers: # should only ever be one Server instance...
ps.stop()
wait(.25)
ps.shutdown()
sys.exit(0)#quits the python session entirely
示例12: clearMemory
def clearMemory(self):
"""
"""
self.sendMessage('SPIE')
self.pause()
reply = self.getResponse(timeout=10)
# should return either FRMT or ESEC to indicate it started
if reply.startswith('FRMT'):
logging.info("BBTK.clearMemory(): "
"Starting full format of BBTK memory")
elif reply.startswith('ESEC'):
logging.info("BBTK.clearMemory(): "
"Starting quick erase of BBTK memory")
else:
logging.error("BBTK.clearMemory(): "
"didn't get a reply from %s" % str(self.com))
return False
# we aren't in a time-critical period so flush messages
logging.flush()
# now wait until we get told 'DONE'
self.com.timeout = 20
retVal = self.com.readline()
if retVal.startswith("DONE"):
logging.info("BBTK.clearMemory(): completed")
# we aren't in a time-critical period so flush messages
logging.flush()
return True
else:
logging.error("BBTK.clearMemory(): "
"Stalled waiting for %s" % str(self.com))
# we aren't in a time-critical period so flush messages
logging.flush()
return False
示例13: _upload
def _upload(stuff):
"""assumes that SELECTOR_FOR_TEST_UPLOAD is a configured http server
"""
selector = SELECTOR_FOR_TEST_UPLOAD
basicAuth = BASIC_AUTH_CREDENTIALS
# make a tmp dir just for testing:
tmp = mkdtemp()
filename = "test.txt"
tmp_filename = os.path.join(tmp, filename)
f = open(tmp_filename, "w+")
f.write(stuff)
f.close()
# get local sha256 before cleanup:
digest = hashlib.sha256()
digest.update(open(tmp_filename).read())
dgst = digest.hexdigest()
# upload:
status = upload(selector, tmp_filename, basicAuth)
shutil.rmtree(tmp) # cleanup; do before asserts
# test
good_upload = True
disgest_match = False
if not status.startswith("success"):
good_upload = False
elif status.find(dgst) > -1:
logging.exp("digests match")
digest_match = True
else:
logging.error("digest mismatch")
logging.flush()
assert good_upload # remote server FAILED to report success
assert digest_match # sha256 mismatch local vs remote file
return int(status.split()[3]) # bytes
示例14: recordStimulusData
def recordStimulusData(self, duration):
"""Record data for a given duration (seconds) and return a list of
events that occured in that period.
"""
self.sendMessage("DSCM")
logging.flush() #we aren't in a time-critical period so flush messages
time.sleep(5.0)
self.sendMessage("TIML")
logging.flush() #we aren't in a time-critical period so flush messages
self.pause()
self.sendMessage("%i" %(int(duration*1000000)), autoLog=False) #BBTK expects this in microsecs
self.pause()
self.sendMessage("RUDS")
logging.flush() #we aren't in a time-critical period so flush messages
示例15: initPyo
def initPyo(rate=44100, stereo=True, buffer=128):
"""setup the pyo (sound) server
"""
global pyoSndServer, Sound, audioDriver, duplex
Sound = SoundPyo
if not 'pyo' in locals():
import pyo # microphone.switchOn() calls initPyo even if audioLib is something else
#subclass the pyo.Server so that we can insert a __del__ function that shuts it down
class Server(pyo.Server):
core=core #make libs class variables so they don't get deleted first
logging=logging
def __del__(self):
self.stop()
self.core.wait(0.5)#make sure enough time passes for the server to shutdown
self.shutdown()
self.core.wait(0.5)#make sure enough time passes for the server to shutdown
self.logging.debug('pyo sound server shutdown')#this may never get printed
maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
maxChnls = min(maxInputChnls, maxOutputChnls)
if maxInputChnls < 1:
logging.warning('%s.initPyo could not find microphone hardware; recording not available' % __name__)
maxChnls = maxOutputChnls
if maxOutputChnls < 1:
logging.error('%s.initPyo could not find speaker hardware; sound not available' % __name__)
core.quit()
#check if we already have a server and kill it
if globals().has_key('pyoSndServer') and hasattr(pyoSndServer,'shutdown'): #if it exists and isn't None!
#this doesn't appear to work!
pyoSndServer.stop()
core.wait(0.5)#make sure enough time passes for the server to shutdown
pyoSndServer.shutdown()
core.wait(0.5)
pyoSndServer.reinit(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
pyoSndServer.boot()
else:
if platform=='win32':
#check for output device/driver
devNames, devIDs=pyo.pa_get_output_devices()
audioDriver,outputID=_bestDriver(devNames, devIDs)
if outputID:
logging.info('Using sound driver: %s (ID=%i)' %(audioDriver, outputID))
else:
logging.warning('No audio outputs found (no speakers connected?')
return -1
#check for valid input (mic)
devNames, devIDs = pyo.pa_get_input_devices()
junk, inputID=_bestDriver(devNames, devIDs)
if inputID:
duplex = bool(maxInputChnls > 0)
else:
duplex=False
else:#for other platforms set duplex to True (if microphone is available)
audioDriver = prefs.general['audioDriver'][0]
duplex = bool(maxInputChnls > 0)
# create the instance of the server:
if platform=='darwin':
#for mac we set the backend using the server audio param
pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
else:
#with others we just use portaudio and then set the OutputDevice below
pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)
pyoSndServer.setVerbosity(1)
if platform=='win32':
pyoSndServer.setOutputDevice(outputID)
if inputID:
pyoSndServer.setInputDevice(inputID)
#do other config here as needed (setDuplex? setOutputDevice?)
pyoSndServer.setDuplex(duplex)
pyoSndServer.boot()
core.wait(0.5)#wait for server to boot before starting te sound stream
pyoSndServer.start()
try:
Sound() # test creation, no play
except pyo.PyoServerStateException:
msg = "Failed to start pyo sound Server"
if platform == 'darwin' and audioDriver != 'portaudio':
msg += "; maybe try prefs.general.audioDriver 'portaudio'?"
logging.error(msg)
core.quit()
logging.debug('pyo sound server started')
logging.flush()