本文整理汇总了Python中psychopy.logging.debug函数的典型用法代码示例。如果您正苦于以下问题:Python debug函数的具体用法?Python debug怎么用?Python debug使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了debug函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: show
def show(self):
# Initially copied from psychopy.gui (which is copyright
# 2011 Jonathan Peirce and available under GPL v3).
buttons = wx.BoxSizer(wx.HORIZONTAL)
OK = wx.Button(self, wx.ID_OK, " OK ")
OK.SetDefault()
buttons.Add(OK)
self.sizer.Add(buttons,1,flag=wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM,border=5)
self.SetSizerAndFit(self.sizer)
self.ShowModal()
self.data=[]
#get data from input fields
for n in range(len(self.inputFields)):
thisName = self.inputFieldNames[n]
thisVal = self.inputFields[n].GetValue()
thisType= self.inputFieldTypes[n]
#try to handle different types of input from strings
debug("%s: %s" %(self.inputFieldNames[n], unicode(thisVal)))
if thisType in [tuple,list,float,int]:
#probably a tuple or list
exec("self.data.append("+thisVal+")")#evaluate it
elif thisType==numpy.ndarray:
exec("self.data.append(numpy.array("+thisVal+"))")
elif thisType in [str,unicode,bool]:
self.data.append(thisVal)
else:
warning('unknown type:'+self.inputFieldNames[n])
self.data.append(thisVal)
self.OK=True
self.Destroy()
示例2: getOriginPathAndFile
def getOriginPathAndFile(self, originPath=None):
"""Attempts to determine the path of the script that created this
data file and returns both the path to that script and its contents.
Useful to store the entire experiment with the data.
If originPath is provided (e.g. from Builder) then this is used
otherwise the calling script is the originPath (fine from a
standard python script).
"""
# self.originPath and self.origin (the contents of the origin file)
if originPath == -1:
return -1, None # the user wants to avoid storing this
elif originPath is None or not os.path.isfile(originPath):
try:
originPath = inspect.getouterframes(
inspect.currentframe())[2][1]
if self.autoLog:
logging.debug("Using %s as origin file" % originPath)
except Exception:
if self.autoLog:
logging.debug("Failed to find origin file using "
"inspect.getouterframes")
return '', ''
if os.path.isfile(originPath): # do we NOW have a path?
origin = codecs.open(originPath, "r", encoding="utf-8").read()
else:
origin = None
return originPath, origin
示例3: OnDropFiles
def OnDropFiles(self, x, y, filenames):
logging.debug('PsychoPyBuilder: received dropped files: %s' % filenames)
for filename in filenames:
if filename.endswith('.psyexp') or filename.lower().endswith('.py'):
self.builder.fileOpen(filename=filename)
else:
logging.warning('dropped file ignored: did not end in .psyexp or .py')
示例4: handleCurrentIndexChanged
def handleCurrentIndexChanged(new_index):
ix = self.inputFields.index(inputBox)
self.data[ix] = inputBox.itemData(new_index).toPyObject()[0]
logging.debug(
"handleCurrentIndexChanged: inputFieldName={0}, "
"selected={1}, type: {2}".format(
label, self.data[ix], type(self.data[ix])))
示例5: _genRsaKeys
def _genRsaKeys(pub="pubkey.pem", priv="privkey.pem", pphr=None, bits=2048):
"""Generate new pub and priv keys, return full path to new files
This is intended for testing purposes, not for general use. Definitely
need to consider: randomness, bits, file permissions, file location (user
home dir?), passphrase creation and usage, passphrase as file generally
not so good, can make sense to have no passphrase, ....
Well-seeded PRNGs are reasonably good; ideally use hardware RNG
gnupg sounds pretty good, cross-platform
"""
logging.debug("_genRsaKeys: start")
# generate priv key:
cmdGEN = [OPENSSL, "genrsa", "-out", priv]
if pphr:
cmdGEN += ["-des3", "-passout", "file:" + pphr]
cmdGEN += [str(bits)]
so = _shellCall(cmdGEN)
# extract pub from priv:
cmdGENpub = [OPENSSL, "rsa", "-in", priv, "-pubout", "-out", pub]
if pphr:
cmdGENpub += ["-passin", "file:" + pphr]
so = _shellCall(cmdGENpub)
return os.path.abspath(pub), os.path.abspath(priv)
示例6: updateFontInfo
def updateFontInfo(self,monospace_only=True):
self._available_font_info.clear()
del self.font_family_styles[:]
import matplotlib.font_manager as font_manager
font_paths=font_manager.findSystemFonts()
def createFontInfo(fp,fface):
fns=(fface.family_name,fface.style_name)
if fns in self.font_family_styles:
pass
else:
self.font_family_styles.append((fface.family_name,fface.style_name))
styles_for_font_dict=self._available_font_info.setdefault(fface.family_name,{})
fonts_for_style=styles_for_font_dict.setdefault(fface.style_name,[])
fi=FontInfo(fp,fface)
fonts_for_style.append(fi)
for fp in font_paths:
if os.path.isfile(fp) and os.path.exists(fp):
try:
face=Face(fp)
if monospace_only:
if face.is_fixed_width:
createFontInfo(fp,face)
else:
createFontInfo(fp,face)
except Exception, e:
logging.debug('Error during FontManager.updateFontInfo(): %s\nFont File: %s'%(str(e),fp))
示例7: sendMessage
def sendMessage(self, message, timeout=0.5, DEBUG=False):
"""Send a command to the photometer and wait an alloted
timeout for a response (Timeout should be long for low
light measurements)
"""
logging.debug("Sending command '%s' to %s" % (message, self.portString)) # send complete message
if message[-1] != "\n":
message += "\n" # append a newline if necess
# flush the read buffer first
self.com.read(self.com.inWaiting()) # read as many chars as are in the buffer
# send the message
for letter in message:
self.com.write(letter) # for PR655 have to send individual chars ! :-/
self.com.flush()
time.sleep(0.2) # PR655 can get cranky if rushed
# get feedback (within timeout)
self.com.setTimeout(timeout)
if message in ["d5\n", "D5\n"]: # we need a spectrum which will have multiple lines
return self.com.readlines()
else:
return self.com.readline()
示例8: _encrypt_rsa_aes256cbc
def _encrypt_rsa_aes256cbc(datafile, pubkeyPem):
"""Encrypt a datafile using openssl to do rsa pub-key + aes256cbc.
"""
logging.debug('_encrypt_rsa_aes256cbc: start')
pwd = _onetimePwd(n=65)
pwdText = _openTmp()
pwdText.write(pwd)
try:
pwdText.seek(0) # go back to start of tmp file
# RSA-PUBKEY-encrypt the password, to file:
pwdFileRsa = PWD_EXT +'_file' + RSA_EXT
cmdRSA = [OPENSSL, 'rsautl', '-in', pwdText.name, '-out', pwdFileRsa,
'-inkey', pubkeyPem, '-keyform', 'PEM',
'-pubin', RSA_PADDING, '-encrypt']
so = _shellCall(cmdRSA)
# AES-256-CBC encrypt datafile, using the one pwd:
dataFileEnc = os.path.abspath(datafile) + AES_EXT
pwdFileRsaNew = _uniqFileName(dataFileEnc + pwdFileRsa.replace('_file', ''))
os.rename(pwdFileRsa, pwdFileRsaNew) # rename the pwd_file to match the datafile
# here gzip the raw datafile?
cmdAES = [OPENSSL, 'enc', '-aes-256-cbc', '-a', '-salt', '-in', datafile,
'-out', dataFileEnc, '-pass', 'file:' + pwdText.name]
so = _shellCall(cmdAES)
finally:
_wipeClose(pwdText)
return os.path.abspath(dataFileEnc), os.path.abspath(pwdFileRsaNew)
示例9: _decrypt_rsa_aes256cbc
def _decrypt_rsa_aes256cbc(dataFileEnc, pwdFileRsa, privkeyPem, passphraseFile=None, outFile=''):
"""Decrypt a file that was encoded by _encrypt_rsa_aes256cbc()
"""
logging.debug('_decrypt_rsa_aes256cbc: start')
pwdText = _openTmp()
try:
# extract unique password from pwdFileRsa using the private key & passphrase
cmdRSA = [OPENSSL, 'rsautl', '-in', pwdFileRsa, '-out', pwdText.name, '-inkey', privkeyPem]
if passphraseFile:
cmdRSA += ['-passin', 'file:' + passphraseFile]
cmdRSA += [RSA_PADDING, '-decrypt']
so, se = _shellCall(cmdRSA, stderr=True) # extract
if 'unable to load Private Key' in se:
raise PrivateKeyError('unable to load Private Key')
elif 'RSA operation error' in se:
raise DecryptError('unable to use Private Key, RSA operation error; wrong key?')
# decide on name for decrypted file:
if outFile:
dataDecrypted = outFile
else:
dataDecrypted = os.path.abspath(dataFileEnc).replace(AES_EXT,'')
# decrypt the data using the recovered password:
cmdAES = [OPENSSL, 'enc', '-d', '-aes-256-cbc', '-a', '-in', dataFileEnc,
'-out', dataDecrypted, '-pass', 'file:'+pwdText.name]
so, se = _shellCall(cmdAES, stderr=True)
finally:
_wipeClose(pwdText)
if 'bad decrypt' in se:
raise DecryptError('_decrypt_rsa_aes256cbc: openssl bad decrypt')
return os.path.abspath(dataDecrypted)
示例10: sendMessage
def sendMessage(self, message, timeout=0.5, DEBUG=False):
"""Send a command to the photometer and wait an alloted
timeout for a response (Timeout should be long for low
light measurements)
"""
if message[-1] != '\n':
message += '\n' # append a newline if necess
# flush the read buffer first
# read as many chars as are in the buffer
self.com.read(self.com.inWaiting())
# send the message
self.com.write(message)
self.com.flush()
# time.sleep(0.1) # PR650 gets upset if hurried!
# get feedback (within timeout limit)
self.com.timeout = timeout
logging.debug(message) # send complete message
if message in ('d5', 'd5\n'):
# we need a spectrum which will have multiple lines
return self.com.readlines()
else:
return self.com.readline()
示例11: showAbout
def showAbout(self, event):
logging.debug("PsychoPyApp: Showing about dlg")
licFile = open(os.path.join(self.prefs.paths["psychopy"], "LICENSE.txt"))
license = licFile.read()
licFile.close()
msg = """For stimulus generation and experimental control in python.
PsychoPy depends on your feedback. If something doesn't work then
let me/us know at [email protected]"""
info = wx.AboutDialogInfo()
# info.SetIcon(wx.Icon(os.path.join(self.prefs.paths['resources'], 'psychopy.png'),wx.BITMAP_TYPE_PNG))
info.SetName("PsychoPy")
info.SetVersion("v" + psychopy.__version__)
info.SetDescription(msg)
info.SetCopyright("(C) 2002-2012 Jonathan Peirce")
info.SetWebSite("http://www.psychopy.org")
info.SetLicence(license)
info.AddDeveloper("Jonathan Peirce")
info.AddDeveloper("Yaroslav Halchenko")
info.AddDeveloper("Jeremy Gray")
info.AddDeveloper("Erik Kastner")
info.AddDeveloper("Michael MacAskill")
info.AddDocWriter("Jonathan Peirce")
info.AddDocWriter("Jeremy Gray")
info.AddDocWriter("Rebecca Sharman")
wx.AboutBox(info)
示例12: push
def push(self, syncPanel=None, progressHandler=None):
"""Push to remote from local copy of the repository
Parameters
----------
syncPanel
progressHandler
Returns
-------
1 if successful
-1 if project deleted on remote
"""
if syncPanel:
syncPanel.statusAppend("\nPushing changes to remote...")
origin = self.repo.remotes.origin
try:
info = self.repo.git.push() # progress=progressHandler
except git.exc.GitCommandError as e:
if ("The project you were looking for could not be found" in
traceback.format_exc()):
# we are pointing to a project at pavlovia but it doesn't exist
# suggest we create it
logging.warning("Project not found on gitlab.pavlovia.org")
return MISSING_REMOTE
else:
raise e
logging.debug('push report: {}'.format(info))
if syncPanel:
syncPanel.statusAppend("done")
if info:
syncPanel.statusAppend("\n{}".format(info))
return 1
示例13: 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
示例14: compareScreenshot
def compareScreenshot(fileName, win, crit=5.0):
"""Compare the current back buffer of the given window with the file
Screenshots are stored and compared against the files under path
kept in TESTS_DATA_PATH. Thus specify relative path to that
directory
"""
#if we start this from a folder below run.py the data folder won't be found
fileName = pjoin(TESTS_DATA_PATH, fileName)
#get the frame from the window
win.getMovieFrame(buffer='back')
frame=win.movieFrames[-1]
win.movieFrames=[]
#if the file exists run a test, if not save the file
if not isfile(fileName):
frame.save(fileName, optimize=1)
raise nose.plugins.skip.SkipTest("Created %s" % basename(fileName))
else:
expected = Image.open(fileName)
expDat = np.array(expected.getdata())
imgDat = np.array(frame.getdata())
rms = (((imgDat-expDat)**2).sum()/len(imgDat))**0.5
logging.debug('PsychoPyTests: RMS=%.3g at threshold=%3.g'
% (rms, crit))
if rms>=crit:
filenameLocal = fileName.replace('.png','_local.png')
frame.save(filenameLocal, optimize=1)
logging.debug('PsychoPyTests: Saving local copy into %s' % filenameLocal)
raise AssertionError("RMS=%.3g at threshold=%.3g. Local copy in %s"
% (rms, crit, filenameLocal))
assert rms<crit # must never fail here
示例15: sendMessage
def sendMessage(self, message, timeout=5.0):
"""Send a command to the photometer and wait an alloted
timeout for a response.
"""
if message[-2:] != '\r\n':
message += '\r\n' # append a newline if necess
# flush the read buffer first
# read as many chars as are in the buffer
self.com.read(self.com.inWaiting())
for attemptN in range(self.maxAttempts):
# send the message
time.sleep(0.1)
self.com.write(message)
self.com.flush()
time.sleep(0.1)
# get reply (within timeout limit)
self.com.timeout = timeout
# send complete message
logging.debug('Sent command:' + message[:-2])
retVal = self.com.readline()
if len(retVal) > 0:
break # we got a reply so can stop trying
return retVal