• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python logging.flush函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中psychopy.logging.flush函数的典型用法代码示例。如果您正苦于以下问题:Python flush函数的具体用法?Python flush怎么用?Python flush使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了flush函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:dgfitch,项目名称:psychopy,代码行数:35,代码来源:idle.py


示例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
开发者ID:bwrc,项目名称:WishGLD,代码行数:33,代码来源:testi.py


示例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
开发者ID:jonathan-mejia,项目名称:psychopy,代码行数:58,代码来源:__init__.py


示例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()
开发者ID:psychopy,项目名称:pyosf,代码行数:11,代码来源:sync.py


示例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()
开发者ID:Lx37,项目名称:psychopy,代码行数:11,代码来源:bits.py


示例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
开发者ID:rainysun,项目名称:psychopy,代码行数:12,代码来源:core.py


示例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
开发者ID:IanEisenberg,项目名称:pytask,代码行数:13,代码来源:exptutils.py


示例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
开发者ID:Lx37,项目名称:psychopy,代码行数:13,代码来源:serialdevice.py


示例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()
开发者ID:mbod,项目名称:vbtg,代码行数:17,代码来源:vbtg.py


示例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()
开发者ID:ChenTzuYin,项目名称:psychopy,代码行数:18,代码来源:serialdevice.py


示例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
开发者ID:MattIBall,项目名称:psychopy,代码行数:18,代码来源:core.py


示例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
开发者ID:balajisriram,项目名称:psychopy,代码行数:33,代码来源:__init__.py


示例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
开发者ID:RSharman,项目名称:psychopy,代码行数:39,代码来源:web.py


示例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
开发者ID:jonathan-mejia,项目名称:psychopy,代码行数:14,代码来源:__init__.py


示例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()
开发者ID:orche22h,项目名称:psychopy,代码行数:84,代码来源:sound.py


示例16: initPyo


#.........这里部分代码省略.........
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    global pyo
    try:
        assert pyo
    except NameError:  # pragma: no cover
        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
    # skip coverage since the class is never used if we have a recent version of pyo
    class _Server(pyo.Server):  # pragma: no cover
        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
    if '.'.join(map(str, pyo.getVersion())) < '0.6.4':
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if 'pyoSndServer' in globals() and hasattr(pyoSndServer,'shutdown'):
        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 is None:
                audioDriver = 'Windows Default Output' #using the default output because we didn't find the one(s) requested
                outputID = pyo.pa_get_default_output()
            if outputID is not None:
                logging.info('Using sound driver: %s (ID=%i)' %(audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(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()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            if inputID is None:
                audioInputName = 'Windows Default Input' #using the default input because we didn't find the one(s) requested
                inputID = pyo.pa_get_default_input()
            if inputID is not None:
                logging.info('Using sound-input driver: %s (ID=%i)' %(audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                maxInputChnls = 0
                duplex=False
        else:#for other platforms set duplex to True (if microphone is available)
            audioDriver = prefs.general['audioDriver'][0]
            maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:  # pragma: no cover
            logging.warning('%s.initPyo could not find microphone hardware; recording not available' % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:  # pragma: no cover
            logging.error('%s.initPyo could not find speaker hardware; sound not available' % __name__)
            return -1

        # create the instance of the server:
        if platform in ['darwin', 'linux2']:
            #for mac/linux 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 is not None:
                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()
开发者ID:9173860,项目名称:psychopy,代码行数:101,代码来源:sound.py


示例17: initPyo

def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    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

    if ".".join(map(str, pyo.getVersion())) < "0.6.4":
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if globals().has_key("pyoSndServer") and hasattr(pyoSndServer, "shutdown"):
        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))
                maxOutputChnls = pyo.pa_get_output_max_channels(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()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            if inputID is not None:
                logging.info("Using sound-input driver: %s (ID=%i)" % (audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(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]
            maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        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__)
            return -1

        # create the instance of the server:
        if platform in ["darwin", "linux2"]:
            # for mac/linux 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()
开发者ID:smathot,项目名称:psychopy,代码行数:94,代码来源:sound.py


示例18: initPyo

def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex
    Sound = SoundPyo
    #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

    #check if we already have a server and kill it
    if hasattr(pyoSndServer,'shutdown'):
        #this doesn't appear to work!
        pyoSndServer.stop()
        core.wait(0.5)#make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        pyoSndServer.reinit(sr=rate, nchnls=2, buffersize=buffer, duplex=1, audio=audioDriver)
        pyoSndServer.boot()
    else:
        #create the instance of the server
        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=True
            else:
                duplex=False
        else:#for other platforms set duplex to True
            audioDriver = prefs.general['audioDriver'][0]
            duplex=True
        if platform=='darwin':
            #for mac we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=2, buffersize=buffer, audio=audioDriver, duplex=duplex)
        else:
            #with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=2, buffersize=buffer, duplex=duplex)
        pyoSndServer.setVerbosity(1)
        if platform=='win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID:
                pyoSndServer.setInputDevice(inputID)
        #do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.boot()
    core.wait(0.5)#wait for server to boot before starting te sound stream
    pyoSndServer.start()
    logging.debug('pyo sound server started')
    logging.flush()
开发者ID:tmintz,项目名称:psychopy,代码行数:62,代码来源:sound.py


示例19: SelectCardSubset

global lastScore
global triggers; triggers=(confInfo[4]=='True') # flag as True when actually recording 

#SETUP CARDS 
cardPrototype = {'G1':0, 'G2':0, 'L1':0, 'L2':0, 'fn':''}

#setup deck of four cards from the whole deck
#deck = SelectCardSubset( 4, N_OF_CARDS )

global currentTgt; currentTgt = (-1, -1, -1, -1)

#TODO: ADD ERROR CHECKING! Here we trust the json files to be correctly formed and valid
confFile = open( '.'+s+'configs'+s+confInfo[3]+'.json' )
config = json.loads( confFile.read() )
confFile.close()
logging.flush()

gameScore = 0
lastScore = 0

triggerAndLog(portCodes['start'], "STR", 0, 0, "START: " + str( startTime ) )

win.setMouseVisible( False )

# - BASELINE VIDEO ------------------------------------------------------------------------------#
movie_filename = "D:/Experiments/video/habit_video_01_wcst.avi"
movie_baseline = visual.MovieStim(win = win, filename = movie_filename, pos = [0,0], size = (1350,1080))
if DEBUGGING_MODE:
    for i in range(25 * 3):
        movie_baseline.draw()
        win.flip()
开发者ID:bwrc,项目名称:WishGLD,代码行数:31,代码来源:WCST_faces_tasktypes_matchingstim_configfile_xpltfrm_andreas.py


示例20: loadFromXML


#.........这里部分代码省略.........
                    self._getXMLparam(params=component.params,
                                      paramNode=paramNode,
                                      componentNode=componentNode)
                compGoodName = self.namespace.makeValid(
                    componentNode.get('name'))
                if compGoodName != componentNode.get('name'):
                    modifiedNames.append(componentNode.get('name'))
                self.namespace.add(compGoodName)
                component.params['name'].val = compGoodName
                routine.append(component)
        # for each component that uses a Static for updates, we need to set
        # that
        for thisRoutine in list(self.routines.values()):
            for thisComp in thisRoutine:
                for thisParamName in thisComp.params:
                    thisParam = thisComp.params[thisParamName]
                    if thisParamName == 'advancedParams':
                        continue  # advanced isn't a normal param
                    elif thisParam.updates and "during:" in thisParam.updates:
                        # remove the part that says 'during'
                        updates = thisParam.updates.split(': ')[1]
                        routine, static = updates.split('.')
                        if routine not in self.routines:
                            msg = ("%s was set to update during %s Static "
                                   "Component, but that component no longer "
                                   "exists")
                            logging.warning(msg % (thisParamName, static))
                        else:
                            self.routines[routine].getComponentFromName(
                                static).addComponentUpdate(
                                thisRoutine.params['name'],
                                thisComp.params['name'], thisParamName)
        # fetch flow settings
        flowNode = root.find('Flow')
        loops = {}
        for elementNode in flowNode:
            if elementNode.tag == "LoopInitiator":
                loopType = elementNode.get('loopType')
                loopName = self.namespace.makeValid(elementNode.get('name'))
                if loopName != elementNode.get('name'):
                    modifiedNames.append(elementNode.get('name'))
                self.namespace.add(loopName)
                loop = eval('%s(exp=self,name="%s")' % (loopType, loopName))
                loops[loopName] = loop
                for paramNode in elementNode:
                    self._getXMLparam(paramNode=paramNode, params=loop.params)
                    # for conditions convert string rep to list of dicts
                    if paramNode.get('name') == 'conditions':
                        param = loop.params['conditions']
                        # e.g. param.val=[{'ori':0},{'ori':3}]
                        try:
                            param.val = eval('%s' % (param.val))
                        except SyntaxError:
                            # This can occur if Python2.7 conditions string
                            # contained long ints (e.g. 8L) and these can't be
                            # parsed by Py3. But allow the file to carry on
                            # loading and the conditions will still be loaded
                            # from the xlsx file
                            pass
                # get condition names from within conditionsFile, if any:
                try:
                    # psychophysicsstaircase demo has no such param
                    conditionsFile = loop.params['conditionsFile'].val
                except Exception:
                    conditionsFile = None
                if conditionsFile in ['None', '']:
                    conditionsFile = None
                if conditionsFile:
                    try:
                        trialList, fieldNames = data.importConditions(
                            conditionsFile, returnFieldNames=True)
                        for fname in fieldNames:
                            if fname != self.namespace.makeValid(fname):
                                duplicateNames.append(fname)
                            else:
                                self.namespace.add(fname)
                    except Exception:
                        pass  # couldn't load the conditions file for now
                self.flow.append(LoopInitiator(loop=loops[loopName]))
            elif elementNode.tag == "LoopTerminator":
                self.flow.append(LoopTerminator(
                    loop=loops[elementNode.get('name')]))
            elif elementNode.tag == "Routine":
                if elementNode.get('name') in self.routines:
                    self.flow.append(self.routines[elementNode.get('name')])
                else:
                    logging.error("A Routine called '{}' was on the Flow but "
                                  "could not be found (failed rename?). You "
                                  "may need to re-insert it".format(
                        elementNode.get('name')))
                    logging.flush()

        if modifiedNames:
            msg = 'duplicate variable name(s) changed in loadFromXML: %s\n'
            logging.warning(msg % ', '.join(list(set(modifiedNames))))
        if duplicateNames:
            msg = 'duplicate variable names: %s'
            logging.warning(msg % ', '.join(list(set(duplicateNames))))
        # if we succeeded then save current filename to self
        self.filename = filename
开发者ID:hoechenberger,项目名称:psychopy,代码行数:101,代码来源:_experiment.py



注:本文中的


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python logging.info函数代码示例发布时间:2022-05-25
下一篇:
Python logging.exp函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap