本文整理汇总了Python中psychopy.logging.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
示例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
示例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
示例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))
示例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
示例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()
示例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
示例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
示例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")
示例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
示例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)
示例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
示例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
示例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)
示例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