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

Python logging.error函数代码示例

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

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



在下文中一共展示了error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _switchToVersion

def _switchToVersion(requestedVersion):
    """Checkout (or clone then checkout) the requested version, set sys.path
    so that the new version will be found when import is called. Upon exit,
    the checked out version remains checked out, but the sys.path reverts.

    NB When installed with pip/easy_install PsychoPy will live in
    a site-packages directory, which should *not* be removed as it may
    contain other relevant and needed packages.
    """
    if not os.path.exists(prefs.paths['userPrefsDir']):
        os.mkdir(prefs.paths['userPrefsDir'])
    try:
        if os.path.exists(VERSIONSDIR):
            _checkout(requestedVersion)
        else:
            _clone(requestedVersion)
    except CalledProcessError as e:
        if 'did not match any file(s) known to git' in e.output:
            msg = _translate("'{}' is not a valid PsychoPy version.")
            logging.error(msg.format(requestedVersion))
            raise RuntimeError(msg)
        else:
            raise

    # make sure the checked-out version comes first on the python path:
    sys.path = [VERSIONSDIR] + sys.path
    logging.exp('Prepended `{}` to sys.path'.format(VERSIONSDIR))
开发者ID:DennisEckmeier,项目名称:psychopy,代码行数:27,代码来源:versionchooser.py


示例2: findPR650

def findPR650(ports=None):
    """DEPRECATED (as of v.1.60.01). Use :func:`psychopy.hardware.findPhotometer()` instead, which
    finds a wider range of devices
    """
    logging.error("DEPRECATED (as of v.1.60.01). Use psychopy.hardware.findPhotometer() instead, which "\
    +"finds a wider range of devices")

    if ports==None:
        if sys.platform=='darwin':
            ports=[]
            #try some known entries in /dev/tty. used by keyspan
            ports.extend(glob.glob('/dev/tty.USA*'))#keyspan twin adapter is usually USA28X13P1.1
            ports.extend(glob.glob('/dev/tty.Key*'))#some are Keyspan.1 or Keyserial.1
            ports.extend(glob.glob('/dev/tty.modem*'))#some are Keyspan.1 or Keyserial.1
            if len(ports)==0: logging.error("couldn't find likely serial port in /dev/tty.* Check for \
                serial port name manually, check drivers installed etc...")
        elif sys.platform=='win32':
            ports = range(11)
    elif type(ports) in [int,float]:
        ports=[ports] #so that we can iterate
    pr650=None
    logging.info('scanning serial ports...\n\t')
    logging.console.flush()
    for thisPort in ports:
        logging.info(str(thisPort)); logging.console.flush()
        pr650 = Photometer(port=thisPort, meterType="PR650", verbose=False)
        if pr650.OK:
            logging.info(' ...OK\n'); logging.console.flush()
            break
        else:
            pr650=None
            logging.info('...Nope!\n\t'); logging.console.flush()
    return pr650
开发者ID:9173860,项目名称:psychopy,代码行数:33,代码来源:calibTools.py


示例3: timingCheckAndLog

def timingCheckAndLog(ts,trialN):
    #check for timing problems and log them
    #ts is a list of the times of the clock after each frame
    interframeIntervs = np.diff(ts)*1000
    #print '   interframe intervs were ',around(interframeIntervs,1) #DEBUGOFF
    frameTimeTolerance=.3 #proportion longer than refreshRate that will not count as a miss
    longFrameLimit = np.round(1000/refreshRate*(1.0+frameTimeTolerance),2)
    idxsInterframeLong = np.where( interframeIntervs > longFrameLimit ) [0] #frames that exceeded 150% of expected duration
    numCasesInterframeLong = len( idxsInterframeLong )
    if numCasesInterframeLong >0 and (not demo):
       longFramesStr =  'ERROR,'+str(numCasesInterframeLong)+' frames were longer than '+str(longFrameLimit)+' ms'
       if demo: 
         longFramesStr += 'not printing them all because in demo mode'
       else:
           longFramesStr += ' apparently screen refreshes skipped, interframe durs were:'+\
                    str( np.around(  interframeIntervs[idxsInterframeLong] ,1  ) )+ ' and was these frames: '+ str(idxsInterframeLong)
       if longFramesStr != None:
                logging.error( 'trialnum='+str(trialN)+' '+longFramesStr )
                if not demo:
                    flankingAlso=list()
                    for idx in idxsInterframeLong: #also print timing of one before and one after long frame
                        if idx-1>=0:
                            flankingAlso.append(idx-1)
                        else: flankingAlso.append(np.NaN)
                        flankingAlso.append(idx)
                        if idx+1<len(interframeIntervs):  flankingAlso.append(idx+1)
                        else: flankingAlso.append(np.NaN)
                    flankingAlso = np.array(flankingAlso)
                    flankingAlso = flankingAlso[np.negative(np.isnan(flankingAlso))]  #remove nan values
                    flankingAlso = flankingAlso.astype(np.integer) #cast as integers, so can use as subscripts
                    logging.info( 'flankers also='+str( np.around( interframeIntervs[flankingAlso], 1) )  ) #because this is not an essential error message, as previous one already indicates error
                      #As INFO, at least it won't fill up the console when console set to WARNING or higher
    return numCasesInterframeLong
开发者ID:alexholcombe,项目名称:attentional-blink,代码行数:33,代码来源:AB.py


示例4: switchOn

def switchOn(sampleRate=44100):
    """Must explicitly switch on the microphone before use, can take several seconds.
    """
    # imports from pyo, creates globals including pyoServer and pyoSamplingRate

    global haveMic
    haveMic = False
    t0 = time.time()
    
    try:
        global Server, Record, Input, Clean_objects, SfPlayer, serverCreated, serverBooted
        from pyo import Server, Record, Input, Clean_objects, SfPlayer, serverCreated, serverBooted
        global getVersion, pa_get_input_devices, pa_get_output_devices
        from pyo import getVersion, pa_get_input_devices, pa_get_output_devices
        haveMic = True
    except ImportError:
        msg = 'Microphone class not available, needs pyo; see http://code.google.com/p/pyo/'
        logging.error(msg)
        raise ImportError(msg)
    
    global pyoSamplingRate
    pyoSamplingRate = sampleRate
    global pyoServer
    if serverCreated():
        pyoServer.setSamplingRate(sampleRate)
        pyoServer.boot()
    else:
        pyoServer = Server(sr=sampleRate, nchnls=2, duplex=1).boot()
    pyoServer.start()

    logging.exp('%s: switch on (%dhz) took %.3fs' % (__file__.strip('.py'), sampleRate, time.time() - t0))
开发者ID:jsalva,项目名称:psychopy,代码行数:31,代码来源:microphone.py


示例5: getInfo

    def getInfo(self):
        """Rather than converting the value of params['Experiment Info']
        into a dict from a string (which can lead to errors) use this function
        :return: expInfo as a dict
        """
        infoStr = self.params['Experiment info'].val.strip()
        if len(infoStr) == 0:
            return {}
        try:
            d = eval(infoStr)
        except SyntaxError:
            """under Python3 {'participant':'', 'session':02} raises an error because 
            ints can't have leading zeros. We will check for those and correct them
            tests = ["{'participant':'', 'session':02}",
                    "{'participant':'', 'session':02}",
                    "{'participant':'', 'session': 0043}",
                    "{'participant':'', 'session':02, 'id':009}",
                    ]
                    """

            def entryToString(match):
                entry = match.group(0)
                digits = re.split(r": *", entry)[1]
                return ':{}'.format(repr(digits))

            # 0 or more spaces, 1-5 zeros, 0 or more digits:
            pattern = re.compile(r": *0{1,5}\d*")
            try:
                d = eval(re.sub(pattern, entryToString, infoStr))
            except SyntaxError:  # still a syntax error, possibly caused by user
                msg = ('Builder Expt: syntax error in '
                              '"Experiment info" settings (expected a dict)')
                logging.error(msg)
                raise AttributeError(msg)
        return d
开发者ID:mmagnuski,项目名称:psychopy,代码行数:35,代码来源:__init__.py


示例6: __init__

    def __init__(self, parent, value=None, order=None):
        """value should be a list of dictionaries with identical field names

        order should be used to specify the order in which the fields appear
        (left to right)
        """
        GlobSizer.__init__(self, hgap=2, vgap=2)
        self.parent = parent
        self.value = value or [{}]
        if type(value) != list or len(value) < 1:
            msg = 'The initial value for a ListWidget must be a list of dicts'
            raise AttributeError(msg)
        # sort fieldNames using order information where possible
        allNames = list(value[0].keys())
        self.fieldNames = []
        if order is None:
            order = []
        for name in order:
            if name not in allNames:
                msg = ('psychopy.dialogs.ListWidget was given a field name '
                       '`%s` in order that was not in the dictionary')
                logging.error(msg % name)
                continue
            allNames.remove(name)
            self.fieldNames.append(name)
        # extend list by the remaining (no explicit order)
        self.fieldNames.extend(allNames)
        # set up controls
        self.createGrid()
开发者ID:ChenTzuYin,项目名称:psychopy,代码行数:29,代码来源:dialogs.py


示例7: _checkoutRequested

def _checkoutRequested(requestedVersion):
    """Look for a tag matching the request, return it if found
    or return None for the search.
    """
    # Check tag of repo
    if getCurrentTag() == requestedVersion:  # nothing to do!
        return 1

    # See if the tag already exists in repos (no need for internet)
    cmd = 'git tag'.split()
    versions = subprocess.check_output(cmd, cwd=VERSIONSDIR)
    if requestedVersion not in versions:
        # Grab new tags
        msg = "Couldn't find version %r locally. Trying github..."
        logging.info(msg % requestedVersion)
        cmd = 'git fetch github'.split()
        out = subprocess.check_output(cmd)
        # after fetching from github check if it's there now!
        versions = subprocess.check_output(['git', 'tag'], cwd=VERSIONSDIR)
        if requestedVersion not in versions:
            msg = "%r is not a valid version. Please choose one of:  %r"
            logging.error(msg % (requestedVersion, versions.split()))
            return 0

    # Checkout the requested tag
    cmd = 'git checkout %s' % requestedVersion
    out = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT,
                                  cwd=VERSIONSDIR)
    logging.debug(out)
    return 1
开发者ID:mry792,项目名称:psychopy,代码行数:30,代码来源:versionchooser.py


示例8: _checkout

def _checkout(requestedVersion):
    """Look for a Maj.min.patch requested version, download (fetch) if needed.
    """
    # Check tag of repo
    if currentTag() == requestedVersion:
        return requestedVersion

    # See if the tag already exists in repos
    if requestedVersion not in _localVersions(forceCheck=True):
        # Grab new tags
        msg = _translate("Couldn't find version {} locally. Trying github...")
        logging.info(msg.format(requestedVersion))
        subprocess.check_output('git fetch github'.split())
        # is requested here now? forceCheck to refresh cache
        if requestedVersion not in _localVersions(forceCheck=True):
            msg = _translate("{} is not currently available.")
            logging.error(msg.format(requestedVersion))
            return ''

    # Checkout the requested tag
    cmd = ['git', 'checkout', requestedVersion]
    out = subprocess.check_output(cmd, stderr=subprocess.STDOUT,
                                  cwd=VERSIONSDIR)
    logging.debug(out)
    logging.exp('Success:  ' + ' '.join(cmd))
    return requestedVersion
开发者ID:DennisEckmeier,项目名称:psychopy,代码行数:26,代码来源:versionchooser.py


示例9: __init__

 def __init__(self, win=None, portName=None, mode=''):
     self.OK=False
     if portName==None:
         if sys.platform == 'darwin':
             portNames = glob.glob('/dev/tty.usbmodemfa*')
             if not portNames:
                 logging.error("Could not connect to Bits Sharp: No serial ports were found at /dev/tty.usbmodemfa*")
                 return None
             else:
                 portName = portNames[0]
         elif sys.platform.startswith('linux'):
             portName = '/dev/ttyACM0'
     self.portName = portName
     self._com = self._connect()
     if self._com:
         self.OK=True
     else:
         return None
     self.info = self.getInfo()
     self.mode = mode
     self.win = win
     if self.win is not None:
         if not hasattr(self.win, '_prepareFBOrender'):
             logging.error("BitsSharp was given an object as win argument but this is not a visual.Window")
         self.win._prepareFBOrender = self._prepareFBOrender
         self.win._finishFBOrender = self._finishFBOrender
         self._setupShaders()
     else:
         logging.warning("%s was not given any PsychoPy win")
开发者ID:lpt100,项目名称:psychopy,代码行数:29,代码来源:bits.py


示例10: rush

def rush(value=True):    
    """Raise the priority of the current thread/process 
    Win32 and OS X only so far - on linux use os.nice(niceIncrement)
    
    Set with rush(True) or rush(False)
    
    Beware and don't take priority until after debugging your code
    and ensuring you have a way out (e.g. an escape sequence of
    keys within the display loop). Otherwise you could end up locked
    out and having to reboot!
    """
    if importCtypesFailed: return False
    
    if value:
        bus = getBusFreq()
        extendedPolicy=_timeConstraintThreadPolicy()
        extendedPolicy.period=bus/160 #number of cycles in hz (make higher than frame rate)
        extendedPolicy.computation=bus/320#half of that period
        extendedPolicy.constrain= bus/640#max period that they should be carried out in
        extendedPolicy.preemptible=1
        extendedPolicy=getThreadPolicy(getDefault=True, flavour=THREAD_TIME_CONSTRAINT_POLICY)
        err=cocoa.thread_policy_set(cocoa.mach_thread_self(), THREAD_TIME_CONSTRAINT_POLICY, 
            ctypes.byref(extendedPolicy), #send the address of the struct
            THREAD_TIME_CONSTRAINT_POLICY_COUNT)
        if err!=KERN_SUCCESS:
            logging.error('Failed to set darwin thread policy, with thread_policy_set')
        else:
            logging.info('Successfully set darwin thread to realtime')
    else:
        #revert to default policy
        extendedPolicy=getThreadPolicy(getDefault=True, flavour=THREAD_STANDARD_POLICY)
        err=cocoa.thread_policy_set(cocoa.mach_thread_self(), THREAD_STANDARD_POLICY, 
            ctypes.byref(extendedPolicy), #send the address of the struct
            THREAD_STANDARD_POLICY_COUNT)
    return True
开发者ID:DiogoamCoutinho,项目名称:stimulus.py,代码行数:35,代码来源:darwin.py


示例11: __init__

 def __init__(self,
              visible=True,
              newPos=None,
              win=None):
     super(Mouse, self).__init__()
     self.visible = visible
     self.lastPos = None
     self.prevPos = None  # used for motion detection and timing
     if win:
         self.win = win
     else:
         try:
             # to avoid circular imports, core.openWindows is defined
             # by visual.py and updated in core namespace;
             # it's circular to "import visual" here in event
             self.win = psychopy.core.openWindows[0]()
             logging.info('Mouse: using default window')
         except (NameError, IndexError):
             logging.error('Mouse: failed to get a default visual.Window'
                           ' (need to create one first)')
             self.win = None
     # for builder: set status to STARTED, NOT_STARTED etc
     self.status = None
     self.mouseClock = psychopy.core.Clock()
     self.movedistance = 0.0
     # if pygame isn't initialised then we must use pyglet
     global usePygame
     if havePygame and not pygame.display.get_init():
         usePygame = False
     if not usePygame:
         global mouseButtons
         mouseButtons = [0, 0, 0]
     self.setVisible(visible)
     if newPos is not None:
         self.setPos(newPos)
开发者ID:mmagnuski,项目名称:psychopy,代码行数:35,代码来源:event.py


示例12: image

    def image(self, filename):
        """Filename, including relative or absolute path. The image
        can be any format that the Python Imaging Library can import
        (almost any). Can also be an image already loaded by PIL.
        """
        filename = pathToString(filename)
        self.__dict__['image'] = filename
        if isinstance(filename, basestring):
            # is a string - see if it points to a file
            if os.path.isfile(filename):
                self.filename = filename
                im = Image.open(self.filename)
                im = im.transpose(Image.FLIP_TOP_BOTTOM)
            else:
                logging.error("couldn't find image...%s" % filename)
                core.quit()
        else:
            # not a string - have we been passed an image?
            try:
                im = filename.copy().transpose(Image.FLIP_TOP_BOTTOM)
            except AttributeError:  # apparently not an image
                logging.error("couldn't find image...%s" % filename)
                core.quit()
            self.filename = repr(filename)  # '<Image.Image image ...>'

        self.size = im.size
        # set correct formats for bytes/floats
        if im.mode == 'RGBA':
            self.imArray = numpy.array(im).astype(numpy.ubyte)
            self.internalFormat = GL.GL_RGBA
        else:
            self.imArray = numpy.array(im.convert("RGB")).astype(numpy.ubyte)
            self.internalFormat = GL.GL_RGB
        self.dataType = GL.GL_UNSIGNED_BYTE
        self._needStrUpdate = True
开发者ID:dgfitch,项目名称:psychopy,代码行数:35,代码来源:simpleimage.py


示例13: calibrateZero

    def calibrateZero(self):
        """Perform a calibration to zero light.

        For early versions of the ColorCAL this had to be called after
        connecting to the device. For later versions the dark calibration
        was performed at the factory and stored in non-volatile memory.

        You can check if you need to run a calibration with::

            ColorCAL.getNeedsCalibrateZero()
        """
        val = self.sendMessage(b"UZC", timeout=1.0)
        if val == 'OK00':
            pass
        elif val == 'ER11':
            logging.error(
                "Could not calibrate ColorCAL2. Is it properly covered?")
            return False
        else:  # unlikely
            logging.warning(
                "Received surprising result from ColorCAL2: %s" % val)
            return False
        # then take a measurement to see if we are close to zero lum (ie is it
        # covered?)
        self.ok, x, y, z = self.measure()
        if y > 3:
            logging.error('There seems to be some light getting to the '
                          'detector. It should be well-covered for zero '
                          'calibration')
            return False
        self._zeroCalibrated = True
        self.calibMatrix = self.getCalibMatrix()
        return True
开发者ID:ChenTzuYin,项目名称:psychopy,代码行数:33,代码来源:colorcal.py


示例14: __init__

    def __init__(self,
                    win,
                    contrast=1.0,
                    gamma=[1.0,1.0,1.0],
                    nEntries=256,
                    mode='bits++',):
        self.win = win
        self.contrast=contrast
        self.nEntries=nEntries
        #set standardised name for mode
        if mode in ['bits','bits++']:
            self.mode = 'bits++'
        elif mode in ['color','color++','colour','colour++']:
            self.mode = 'color++'
        elif mode in ['mono','mono++']:
            self.mode = 'mono++'
        else:
            logging.error("Unknown mode '%s' for BitsBox" %mode)

        if len(gamma)>2: # [Lum,R,G,B] or [R,G,B]
            self.gamma=gamma[-3:]
        else:
            self.gamma = [gamma, gamma, gamma]

        if init():
            setVideoMode(NOGAMMACORRECT|VIDEOENCODEDCOMMS)
            self.initialised=True
            logging.debug('found and initialised bits++')
        else:
            self.initialised=False
            logging.warning("couldn't initialise bits++")

        if self.mode == 'bits++':
            #do the processing
            self._HEADandLUT = numpy.zeros((524,1,3),numpy.uint8)
            self._HEADandLUT[:12,:,0] = numpy.asarray([ 36, 63, 8, 211, 3, 112, 56, 34,0,0,0,0]).reshape([12,1])#R
            self._HEADandLUT[:12,:,1] = numpy.asarray([ 106, 136, 19, 25, 115, 68, 41, 159,0,0,0,0]).reshape([12,1])#G
            self._HEADandLUT[:12,:,2] = numpy.asarray([ 133, 163, 138, 46, 164, 9, 49, 208,0,0,0,0]).reshape([12,1])#B
            self.LUT=numpy.zeros((256,3),'d')#just a place holder
            self.setLUT()#this will set self.LUT and update self._LUTandHEAD
        elif haveShaders:
            self.monoModeShader = shaders.compileProgram(fragment=shaders.bitsMonoModeFrag,
                                   attachments=[shaders.gammaCorrectionFrag])
            self.colorModeShader =shaders.compileProgram(fragment=shaders.bitsColorModeFrag,
                                   attachments=[shaders.gammaCorrectionFrag])
            GL.glUseProgram(self.colorModeShader)
            prog = self.colorModeShader
            GL.glUniform1f(GL.glGetUniformLocation(prog, 'sampleSpacing'), 1.0)
            #Set default encoding gamma for power-law shader to (1.0, 1.0, 1.0):
            GL.glUniform3f(GL.glGetUniformLocation(prog, 'ICMEncodingGamma'), 1.0, 1.0, 1.0)
            # Default min and max luminance is 0.0 to 1.0, therefore reciprocal 1/range is also 1.0:
            GL.glUniform3f(GL.glGetUniformLocation(prog, 'ICMMinInLuminance'), 0.0, 0.0, 0.0)
            GL.glUniform3f(GL.glGetUniformLocation(prog, 'ICMMaxInLuminance'), 1.0, 1.0, 1.0)
            GL.glUniform3f(GL.glGetUniformLocation(prog, 'ICMReciprocalLuminanceRange'), 1.0, 1.0, 1.0)
            # Default gain to postmultiply is 1.0:
            GL.glUniform3f(GL.glGetUniformLocation(prog, 'ICMOutputGain'), 1.0, 1.0, 1.0)
            # Default bias to is 0.0:
            GL.glUniform3f(GL.glGetUniformLocation(prog, 'ICMOutputBias'), 0.0, 0.0, 0.0)
            GL.glUniform2f(GL.glGetUniformLocation(prog, 'ICMClampToColorRange'), 0.0, 1.0)
            GL.glUseProgram(0)
开发者ID:crsltd-opensource,项目名称:pycrsltd,代码行数:60,代码来源:bits.py


示例15: wav2flac

def wav2flac(path, keep=True):
    """Lossless compression: convert .wav file (on disk) to .flac format.

    If `path` is a directory name, convert all .wav files in the directory.

    `keep` to retain the original .wav file(s), default `True`.
    """
    flac_path = _getFlacPath()
    wav_files = []
    if path.endswith(".wav"):
        wav_files = [path]
    elif type(path) == str and os.path.isdir(path):
        wav_files = glob.glob(os.path.join(path, "*.wav"))
    if len(wav_files) == 0:
        logging.warn("failed to find .wav file(s) from %s" % path)
        return None
    flac_files = []
    for wavfile in wav_files:
        flacfile = wavfile.strip(".wav") + ".flac"
        flac_cmd = [flac_path, "-8", "-f", "--totally-silent", "-o", flacfile, wavfile]
        __, se = core.shellCall(flac_cmd, stderr=True)
        if se or not os.path.isfile(flacfile):  # just try again
            # ~2% incidence when recording for 1s, 650+ trials
            # never got two in a row; core.wait() does not help
            logging.warn("Failed to convert to .flac; trying again")
            __, se = core.shellCall(flac_cmd, stderr=True)
            if se:
                logging.error(se)
        if not keep:
            os.unlink(wavfile)
        flac_files.append(flacfile)
    if len(wav_files) == 1:
        return flac_files[0]
    else:
        return flac_files
开发者ID:rpbaxter,项目名称:psychopy,代码行数:35,代码来源:microphone.py


示例16: __init__

    def __init__(self, id):
        """An object to control a multi-axis joystick or gamepad

        .. note:

            You do need to be flipping frames (or dispatching events manually)
            in order for the values of the joystick to be updated.

        :Known issues:

            Currently under pyglet backends the axis values initialise to zero
            rather than reading the current true value. This gets fixed on the
            first change to each axis.
        """
        self.id=id
        if backend=='pyglet':
            joys=pyglet_input.get_joysticks()
            if id>=len(joys):
                logging.error("You don't have that many joysticks attached (remember that the first joystick has id=0 etc...)")
            else:
                self._device=joys[id]
                self._device.open()
                self.name=self._device.device.name
            if len(visual.openWindows)==0:
                logging.error("You need to open a window before creating your joystick")
            else:
                for win in visual.openWindows:
                    win._eventDispatchers.append(self._device.device)
        else:
            pygame.joystick.init()
            self._device=pygame.joystick.Joystick(id)
            self._device.init()
            self.name=self._device.get_name()
开发者ID:Lx37,项目名称:psychopy,代码行数:33,代码来源:__init__.py


示例17: expression2js

def expression2js(expr):
    """Convert a short expression (e.g. a Component Parameter) Python to JS"""

    # if the code contains a tuple (anywhere), convert parenths to be list.
    # This now works for compounds like `(2*(4, 5))` where the inner
    # parenths becomes a list and the outer parens indicate priority.
    # This works by running an ast transformer class to swap the contents of the tuple
    # into a list for the number of tuples in the expression.
    try:
        syntaxTree = ast.parse(expr)
    except Exception as err:
        logging.error(err)
        syntaxTree = ast.parse(unicode(expr))

    for node in ast.walk(syntaxTree):
        TupleTransformer().visit(node)  # Transform tuples to list
        # for py2 using 'unicode_literals' we don't want
        if isinstance(node, ast.Str) and type(node.s)==bytes:
            node.s = unicode(node.s, 'utf-8')
        elif isinstance(node, ast.Str) and node.s.startswith("u'"):
            node.s = node.s[1:]
        if isinstance(node, ast.Name):
            if node.id == 'undefined':
                continue
            node.id = namesJS[node.id]
    jsStr = unparse(syntaxTree).strip()
    return jsStr
开发者ID:dgfitch,项目名称:psychopy,代码行数:27,代码来源:py2js.py


示例18: 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


示例19: playback

    def playback(self, block=True, loops=0, stop=False, log=True):
        """Plays the saved .wav file, as just recorded or resampled. Execution
        blocks by default, but can return immediately with `block=False`.

        `loops` : number of extra repetitions; 0 = play once

        `stop` : True = immediately stop ongoing playback (if there is one), and return
        """
        if not self.savedFile or not os.path.isfile(self.savedFile):
            msg = "%s: Playback requested but no saved file" % self.loggingId
            logging.error(msg)
            raise ValueError(msg)

        if stop:
            if hasattr(self, "current_recording") and self.current_recording.status == PLAYING:
                self.current_recording.stop()
            return

        # play this file:
        name = self.name + ".current_recording"
        self.current_recording = sound.Sound(self.savedFile, name=name, loops=loops)
        self.current_recording.play()
        if block:
            core.wait(self.duration * (loops + 1))  # set during record()

        if log and self.autoLog:
            if loops:
                logging.exp(
                    "%s: Playback: play %.3fs x %d (est) %s"
                    % (self.loggingId, self.duration, loops + 1, self.savedFile)
                )
            else:
                logging.exp("%s: Playback: play %.3fs (est) %s" % (self.loggingId, self.duration, self.savedFile))
开发者ID:rpbaxter,项目名称:psychopy,代码行数:33,代码来源:microphone.py


示例20: flac2wav

def flac2wav(path, keep=True):
    """Uncompress: convert .flac file (on disk) to .wav format (new file).

    If `path` is a directory name, convert all .flac files in the directory.

    `keep` to retain the original .flac file(s), default `True`.
    """
    flac_path = _getFlacPath()
    flac_files = []
    if path.endswith('.flac'):
        flac_files = [path]
    elif type(path) == str and os.path.isdir(path):
        flac_files = glob.glob(os.path.join(path, '*.flac'))
    if len(flac_files) == 0:
        logging.warn('failed to find .flac file(s) from %s' % path)
        return None
    wav_files = []
    for flacfile in flac_files:
        wavname = flacfile.strip('.flac') + '.wav'
        flac_cmd = [flac_path, "-d", "--totally-silent",
                    "-f", "-o", wavname, flacfile]
        _junk, se = core.shellCall(flac_cmd, stderr=True)
        if se:
            logging.error(se)
        if not keep:
            os.unlink(flacfile)
        wav_files.append(wavname)
    if len(wav_files) == 1:
        return wav_files[0]
    else:
        return wav_files
开发者ID:jonathanoroberts,项目名称:psychopy,代码行数:31,代码来源:microphone.py



注:本文中的psychopy.logging.error函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python logging.exp函数代码示例发布时间:2022-05-25
下一篇:
Python logging.debug函数代码示例发布时间: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