def _getSvnVersion(filename): """Tries to discover the svn version (revision #) for a file. Not thoroughly tested; completely untested on Windows Vista, Win 7, FreeBSD :Author: - 2010 written by Jeremy Gray """ if not (os.path.exists(filename) and os.path.isdir(os.path.join(os.path.dirname(filename), '.svn'))): return None, None, None svnRev, svnLastChangedRev, svnUrl = None, None, None if sys.platform in ['darwin', 'freebsd'] or sys.platform.startswith('linux'): try: svninfo = shellCall(['svn', 'info', filename]) # expects a filename, not dir except: svninfo = '' for line in svninfo.splitlines(): if line.startswith('URL:'): svnUrl = line.split()[1] elif line.startswith('Revision: '): svnRev = line.split()[1] elif line.startswith('Last Changed Rev'): svnLastChangedRev = line.split()[3] else: # worked for me on Win XP sp2 with TortoiseSVN (SubWCRev.exe) try: stdout = shellCall(['subwcrev', filename]) except: stdout = '' for line in stdout.splitlines(): if line.startswith('Last committed at revision'): svnRev = line.split()[4] elif line.startswith('Updated to revision'): svnLastChangedRev = line.split()[3] return svnRev, svnLastChangedRev, svnUrl
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: wavfile = flacfile.strip(".flac") + ".wav" flac_cmd = [flac_path, "-d", "--totally-silent", "-f", "-o", wavfile, flacfile] __, se = core.shellCall(flac_cmd, stderr=True) if se or not os.path.isfile(flacfile): # just try again logging.warn("Failed to convert to .wav; trying again") __, se = core.shellCall(flac_cmd, stderr=True) if se: logging.error(se) if not keep: os.unlink(flacfile) wav_files.append(wavfile) if len(wav_files) == 1: return wav_files[0] else: return wav_files
def _getHgVersion(filename): """Tries to discover the mercurial (hg) parent and id of a file. Not thoroughly tested; untested on Windows Vista, Win 7, FreeBSD :Author: - 2010 written by Jeremy Gray """ dirname = os.path.dirname if (not os.path.exists(filename) or not os.path.isdir(os.path.join(dirname(filename), '.hg'))): return None try: hgParentLines, err = shellCall(['hg', 'parents', filename], stderr=True) changeset = hgParentLines.splitlines()[0].split()[-1] except Exception: changeset = '' try: hgID, err = shellCall(['hg', 'id', '-nibt', dirname(filename)], stderr=True) except Exception: if err: hgID = '' if len(hgID) or len(changeset): return hgID.strip() + ' | parent: ' + changeset.strip() else: return None
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
def _getHgVersion(file): """Tries to discover the mercurial (hg) parent and id of a file. Not thoroughly tested; completely untested on Windows Vista, Win 7, FreeBSD :Author: - 2010 written by Jeremy Gray """ if not os.path.exists(file) or not os.path.isdir(os.path.join(os.path.dirname(file),'.hg')): return None try: hgParentLines,err = shellCall('hg parents "'+file+'"', stderr=True) changeset = hgParentLines.splitlines()[0].split()[-1] except: changeset = '' #else: changeset = hgParentLines.splitlines()[0].split()[-1] try: hgID,err = shellCall('hg id -nibt "'+os.path.dirname(file)+'"', stderr=True) except: if err: hgID = '' if len(hgID) or len(changeset): return hgID.strip()+' | parent: '+changeset.strip() else: return None
def OnClickedVSTMDemo(self, event): btn = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btn)) core.shellCall([ sys.executable, "VSTMPsychopyFiles/VSTM_CirclesInGrid_DEMOv1.py", self.PartID.GetValue() ]) self.VSTMDEMOCB.SetValue(True)
def OnClickedFRTDemo(self, event): btn = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btn)) core.shellCall([ sys.executable, "FRTPsychopyFiles/FRTDemo_GUI.py", self.PartID.GetValue() ]) self.FRTDEMOCB.SetValue(True)
def OnClickedR5C6(self, event): # Use the tag to keep track of the run number self.DMSTag = self.DMSTag + 1 btnR5C6Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s"%(btnR5C6Label)) print("Load levels: %s"%(self.DMSBlockLoadLevels)) core.shellCall([sys.executable, "../DMSPsychopyFiles/DMS_Adaptive5Load_v4NP.py", self.PartID.GetValue(), self.VisitFolderPath, self.DMSBlockLoadLevels, self.DMSFontSize, 'BehRun%d'%(self.DMSTag)]) self.cbR5C6.SetValue(True)
def OnClickedR9C3(self, event): btnR9C3Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR9C3Label)) core.shellCall([ sys.executable, "../Matrices/MatricesWClockMainv2.py", self.PartID.GetValue(), self.VisitFolderPath ]) self.cbR9C3.SetValue(True)
def OnClickedR1C3(self, event): btnR1C3Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR1C3Label)) core.shellCall([ sys.executable, "../Stroop/StroopWordv1.py", self.PartID.GetValue(), self.VisitFolderPath ]) self.cbR1C3.SetValue(True)
def OnClickedR8C2(self, event): btnR8C2Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR8C2Label)) core.shellCall([ sys.executable, "../PatternComparison/PatternComparison_v2.py", self.PartID.GetValue(), self.VisitFolderPath ]) self.cbR8C2.SetValue(True)
def OnClickedR7C3(self, event): btnR7C3Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR7C3Label)) core.shellCall([ sys.executable, "../DigitSpan/BackwardDigitSpan.py", self.PartID.GetValue(), self.VisitFolderPath ]) self.cbR7C3.SetValue(True)
def OnClickedR5C2(self, event): btnR5C2Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR5C2Label)) core.shellCall([ sys.executable, "../DMSPsychopyFiles/DMSDemo_GUI_v2.py", self.PartID.GetValue(), self.VisitFolderPath, self.DMSFontSize ]) self.cbR5C2.SetValue(True)
def OnClickedDMSDemo(self, event): btn = event.GetEventObject().GetLabel() print "Label of pressed button = ", btn core.shellCall([ sys.executable, "DMSPsychopyFiles/DMSDemo_GUI.py", self.PartID.GetValue(), '60' ]) self.DMSDEMOCB.SetValue(True)
def test_stdin_and_stderr(self): echo, se = shellCall([self.cmd, self.msg], stdin='echo', stderr=True) assert echo == self.msg assert se == '' echo, se = shellCall(self.cmd + ' ' + self.msg, stdin='echo', stderr=True) assert echo == self.msg assert se == ''
def OnClickedDMSStair(self, event): self.DMSStairCaseDateStr = data.getDateStr() btn = event.GetEventObject().GetLabel() print "Label of pressed button = ", btn core.shellCall([ sys.executable, "DMSPsychopyFiles/DMSStairCase_v4_forBehav.py", self.PartID.GetValue() ]) self.LoadDMSCapacity(self)
def OnClickedDMSDemo(self, event): FontSize = '60' btn = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btn)) core.shellCall([ sys.executable, "DMSPsychopyFiles/DMSDemo_GUI.py", self.PartID.GetValue(), FontSize ]) self.DMSDEMOCB.SetValue(True)
def OnClickedR3C2(self, event): btnR3C2Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR3C2Label)) core.shellCall([ sys.executable, "../VSTMPsychopyFiles/VSTM_CirclesInGrid_DEMOv2.py", self.PartID.GetValue(), self.VisitFolderPath ]) self.cbR3C2.SetValue(True)
def OnClickedRMemC2(self, event): btnMemC2Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnMemC2Label)) core.shellCall([ sys.executable, "../SelectiveReminding/SelectiveRemindingWithTimerSoundsv1.py", self.PartID.GetValue(), self.VisitFolderPath ]) self.cbRMemC2.SetValue(True)
def OnClickedR5C3(self, event): btnR5C3Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR5C3Label)) core.shellCall([ sys.executable, "../DMSPsychopyFiles/DMSStairCase_v4.py", self.PartID.GetValue(), self.VisitFolderPath ]) self.LoadDMSCapacity(True) self.cbR5C3.SetValue(True)
def OnClickedDMSStair(self, event): FontSize = '60' self.DMSStairCaseDateStr = data.getDateStr() btn = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btn)) core.shellCall([ sys.executable, "DMSPsychopyFiles/DMSStairCase_v3.py", self.PartID.GetValue(), FontSize ]) self.LoadDMSCapacity(self)
def OnClickedFRTBlock(self, event): btn = event.GetEventObject().GetLabel() print("Label of pressed button = " % (btn)) print self.PartID.GetValue() print self.FRTBlockLoadLevels core.shellCall([ sys.executable, "FRTPsychopyFiles/FRT_Adaptive.py", self.PartID.GetValue(), self.FRTBlockLoadLevels ]) self.FRTBlockCB1.SetValue(True)
def OnClickedFRTStair(self, event): btn = event.GetEventObject().GetLabel() print "Label of pressed button = ", btn self.FRTStairCaseDateStr = data.getDateStr() core.shellCall([ sys.executable, "FRTPsychopyFiles/FRTStairCase_v1.py", self.PartID.GetValue() ]) # after the task is run read the capicity file self.LoadFRTCapacity(self)
def OnClickedRMemC6(self, event): btnMemC6Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnMemC6Label)) #core.shellCall([sys.executable, "../SelectiveReminding/SRTRecogSequentialPres.py", self.PartID.GetValue(), self.VisitFolderPath]) core.shellCall([ sys.executable, "../SelectiveReminding/SRTRecogSequentialPresSounds.py", self.PartID.GetValue(), self.VisitFolderPath ]) self.cbRMemC6.SetValue(True)
def OnClickedR10C4(self, event): self.NBackTag = self.NBackTag + 1 btnR10C4Label = event.GetEventObject().GetLabel() print("Label of pressed button = NBack: %s" % (btnR10C4Label)) core.shellCall([ sys.executable, "../NBack/NBackPassConfigFile.py", self.PartID.GetValue(), self.VisitFolderPath, 'MRIRun%02d' % (self.NBackTag), 'NBack_fMRI_Config', 'Fixed' ]) self.cbR10C4.SetValue(True)
def OnClickedVSTMStair(self, event): btn = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btn)) self.VSTMStairCaseDateStr = data.getDateStr() core.shellCall([ sys.executable, "VSTMPsychopyFiles/VSTM_CirclesInGridStaircase_v2.py", self.PartID.GetValue() ]) # after the task is run read the capicity file self.LoadVSTMCapacity(self)
def OnClickedR3C3(self, event): btnR3C3Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR3C3Label)) core.shellCall([ sys.executable, "../VSTMPsychopyFiles/VSTM_CirclesInGridStaircase_v3.py", self.PartID.GetValue(), self.VisitFolderPath ]) # Once the staircase is run, load up the file that is created and display it self.LoadVSTMCapacity(self) self.cbR3C3.SetValue(True)
def OnClickedR3C4(self, event): self.VSTMTag = self.VSTMTag + 1 btnR3C4Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s"%(btnR3C4Label)) #VSTMCapacity = 7 # self.VSTMBlockLoadLevels = self.CreateVSTMList5(self.VSTMCapacity) # print('With a capacity of %0.1f, the load levels will be:'%(float(self.VSTMCapacity))) print(self.VSTMBlockLoadLevels) core.shellCall([sys.executable, "../VSTMPsychopyFiles/VSTM_PassConfigFile.py", self.PartID.GetValue(), self.VisitFolderPath, self.VSTMBlockLoadLevels, 'BehRun%d'%(self.VSTMTag),'VSTM_Behav_Config','True']) #core.shellCall([sys.executable, "../VSTMPsychopyFiles/VSTM_CirclesInGrid_v6.py", self.PartID.GetValue(), self.VisitFolderPath, self.VSTMBlockLoadLevels, 'BehRun%d'%(self.VSTMTag)]) self.cbR3C4.SetValue(True)
def test_shellCall(): msg = 'echo' cmd = ('grep', 'findstr')[sys.platform == 'win32'] for arg1 in [[cmd, msg], cmd+' '+msg]: echo = shellCall(arg1, stdin=msg) assert echo == msg echo, se = shellCall(arg1, stdin=msg, stderr=True) assert echo == msg echo, se = shellCall(12, stdin=msg) assert echo == None
def test_shellCall(): msg = 'echo' cmd = ('grep', 'findstr')[sys.platform == 'win32'] for arg1 in [[cmd, msg], cmd + ' ' + msg]: echo = shellCall(arg1, stdin=msg) assert echo == msg echo, se = shellCall(arg1, stdin=msg, stderr=True) assert echo == msg echo, se = shellCall(12, stdin=msg) assert echo == None
def _setSystemUserInfo(self): # machine name self['systemHostName'] = platform.node() # platform name, etc if sys.platform in ['darwin']: OSXver, junk, architecture = platform.mac_ver() platInfo = 'darwin ' + OSXver + ' ' + architecture # powerSource = ... elif sys.platform in ['linux2']: platInfo = 'linux2 ' + platform.release() # powerSource = ... elif sys.platform in ['win32']: platInfo = 'windowsversion=' + repr(sys.getwindowsversion()) # powerSource = ... else: platInfo = ' [?]' # powerSource = ... self['systemPlatform'] = platInfo #self['systemPowerSource'] = powerSource # count all unique people (user IDs logged in), and find current user name & UID self['systemUser'], self['systemUserID'] = _getUserNameUID() try: users = shellCall("who -q").splitlines()[0].split() self['systemUsersCount'] = len(set(users)) except: self['systemUsersCount'] = False # when last rebooted? try: lastboot = shellCall("who -b").split() self['systemRebooted'] = ' '.join(lastboot[2:]) except: # windows sysInfo = shellCall('systeminfo').splitlines() lastboot = [ line for line in sysInfo if line.find("System Up Time") == 0 or line.find("System Boot Time") == 0 ] lastboot += ['[?]'] # put something in the list just in case self['systemRebooted'] = lastboot[0].strip() # is R available (for stats)? try: Rver, err = shellCall("R --version", stderr=True) Rversion = Rver.splitlines()[0] if Rversion.find('R version') == 0: self['systemRavailable'] = Rversion.strip() else: raise except: self['systemRavailable'] = False """try:
def _getFlacPath(flac_exe=''): """Return full path to flac binary, using a cached value if possible. """ global FLAC_PATH if FLAC_PATH is None: if sys.platform == 'win32': if os.path.isfile(flac_exe): FLAC_PATH = flac_exe else: FLAC_PATH = core.shellCall(['where', '/r', 'C:\\', 'flac']) else: FLAC_PATH = core.shellCall(['/usr/bin/which', 'flac']) logging.info('set FLAC_PATH to %s' % FLAC_PATH) return FLAC_PATH
def __init__(self): from psychopy import core import os # should be writable: noopPath = os.path.join(psychopy.prefs.paths['userPrefsDir'], 'showgui_hack.py') # code to open & immediately close a gui (= invisibly): if not os.path.isfile(noopPath): code = """from psychopy import gui dlg = gui.Dlg().Show() # non-blocking try: dlg.Destroy() # might as well except: pass""".replace(' ', '') with open(noopPath, 'wb') as fd: fd.write(code) core.shellCall([sys.executable, noopPath]) # append 'w' for pythonw seems not needed
def OnClickedWORDDemo(self, event): print(self.CounterBalCB.GetValue()) btn = event.GetEventObject().GetLabel() CounterBalFlag = str(self.CounterBalCB.GetValue()) print("Label of pressed button = %s" % (btn)) Tag = 'WordDemo' print self.PartID.GetValue() # print self.DMSBlockLoadLevels #core.shellCall([sys.executable, "DMSPsychopyFiles/DMS_Adaptive_v2.py", self.PartID.GetValue(), self.DMSBlockLoadLevels]) core.shellCall([ sys.executable, "SemanticRichness/BlockBased/SemanticRichnessBlockBasedDEMOv2.py", self.PartID.GetValue(), CounterBalFlag, Tag ])
def _setSystemUserInfo(self): # machine name self['systemHostName'] = platform.node() # platform name, etc if sys.platform in ['darwin']: OSXver, junk, architecture = platform.mac_ver() platInfo = 'darwin '+OSXver+' '+architecture # powerSource = ... elif sys.platform in ['linux2']: platInfo = 'linux2 '+platform.release() # powerSource = ... elif sys.platform in ['win32']: platInfo = 'windowsversion='+repr(sys.getwindowsversion()) # powerSource = ... else: platInfo = ' [?]' # powerSource = ... self['systemPlatform'] = platInfo #self['systemPowerSource'] = powerSource # count all unique people (user IDs logged in), and find current user name & UID self['systemUser'],self['systemUserID'] = _getUserNameUID() try: users = shellCall("who -q").splitlines()[0].split() self['systemUsersCount'] = len(set(users)) except: self['systemUsersCount'] = False # when last rebooted? try: lastboot = shellCall("who -b").split() self['systemRebooted'] = ' '.join(lastboot[2:]) except: # windows sysInfo = shellCall('systeminfo').splitlines() lastboot = [line for line in sysInfo if line.find("System Up Time") == 0 or line.find("System Boot Time") == 0] lastboot += ['[?]'] # put something in the list just in case self['systemRebooted'] = lastboot[0].strip() # is R available (for stats)? try: Rver,err = shellCall("R --version",stderr=True) Rversion = Rver.splitlines()[0] if Rversion.find('R version') == 0: self['systemRavailable'] = Rversion.strip() else: raise except: self['systemRavailable'] = False """try:
def OnClickedR3C4(self, event): btnR3C4Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR3C4Label)) VSTMCapacity = 7 self.VSTMBlockLoadLevels = self.CreateVSTMList5(VSTMCapacity) print('With a capacity of %0.1f, the load levels will be:' % (VSTMCapacity)) print(self.VSTMBlockLoadLevels) core.shellCall([ sys.executable, "../VSTMPsychopyFiles/VSTM_CirclesInGrid_v6.py", self.PartID.GetValue(), self.VisitFolderPath, self.VSTMBlockLoadLevels ]) self.cbR3C4.SetValue(True)
def OnClickedR5C7(self, event): # Use the tag to keep track of the run number self.DMSTag = self.DMSTag + 1 btnR5C7Label = event.GetEventObject().GetLabel() print("Label of pressed button = %s" % (btnR5C7Label)) self.DMSBlockLoadLevels = self.CreateDMSList5(self.DMSCapacity) print('With a capacity of %0.1f, the load levels will be:' % (float(self.DMSCapacity))) print(self.DMSBlockLoadLevels) core.shellCall([ sys.executable, "../DMSPsychopyFiles/DMS_Adaptive5Load_v4_FMRI.py", self.PartID.GetValue(), self.VisitFolderPath, self.DMSBlockLoadLevels, self.DMSFontSize, 'MRIRun%d' % (self.DMSTag) ]) self.cbR5C7.SetValue(True)
def _wizard(self, selector, arg=""): from psychopy import core wizard = os.path.join(self.prefs.paths["psychopy"], "wizard.py") so, se = core.shellCall([sys.executable, wizard, selector, arg], stderr=True) if se and self.prefs.app["debugMode"]: print se # stderr contents; sometimes meaningless
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 = [] path = pathToString(path) 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
def test_shellCall(): if PY3: # This call to shellCall from tests is failing from Python3 # but maybe it just isn't a great test anyway?! # shellCall is used by PsychoPy Tools>Run and works on Py3 there! pytest.xfail(reason="Failing on Py3") msg = 'echo' cmd = ('grep', 'findstr')[sys.platform == 'win32'] for arg1 in [[cmd, msg], cmd+' '+msg]: echo = shellCall(arg1, stdin=msg) assert echo == msg echo, se = shellCall(arg1, stdin=msg, stderr=True) assert echo == msg echo, se = shellCall(12, stdin=msg) assert echo is None
def _wizard(self, selector, arg=''): from psychopy import core wizard = os.path.join(self.prefs.paths['psychopy'], 'wizard.py') so, se = core.shellCall([sys.executable, wizard, selector, arg], stderr=True) if se and self.prefs.app['debugMode']: print se # stderr contents; sometimes meaningless
def _getUserNameUID(): """Return user name, UID. UID values can be used to infer admin-level: -1=undefined, 0=full admin/root, >499=assume non-admin/root (>999 on debian-based) :Author: - 2010 written by Jeremy Gray """ try: user = os.environ['USER'] except KeyError: user = os.environ['USERNAME'] uid = '-1' try: if sys.platform not in ['win32']: uid = shellCall('id -u') else: try: uid = '1000' if ctypes.windll.shell32.IsUserAnAdmin(): uid = '0' except: raise except: pass return str(user), int(uid)
def _wizard(self, selector, arg=''): from psychopy import core wizard = os.path.join( self.prefs.paths['psychopy'], 'tools', 'wizard.py') so, se = core.shellCall( [sys.executable, wizard, selector, arg], stderr=True) if se and self.prefs.app['debugMode']: print(se) # stderr contents; sometimes meaningless
def _prepare(self): """Prep for bench-marking; currently just RAM-related on mac""" if sys.platform == 'darwin': try: core.shellCall('purge') # free up physical memory if possible except OSError: pass elif sys.platform == 'win32': # This will run in background, perhaps best to launch it to run overnight the day before benchmarking: # %windir%\system32\rundll32.exe advapi32.dll,ProcessIdleTasks # rundll32.exe advapi32.dll,ProcessIdleTasks pass elif sys.platform.startswith('linux'): # as root: sync; echo 3 > /proc/sys/vm/drop_caches pass else: pass
def _getHashGitHead(dir=''): origDir = os.getcwd() os.chdir(dir) try: git_hash = shellCall("git rev-parse --verify HEAD") except OSError: os.chdir(origDir) return None except WindowsError: # not defined on mac; OSError should catch lack of git os.chdir(origDir) return None os.chdir(origDir) git_branches = shellCall("git branch") git_branch = [line.split()[1] for line in git_branches.splitlines() if line.startswith('*')] if len(git_branch): return git_branch[0] + ' ' + git_hash.strip() else: # dir is not a git repo return None
def wav2flac(path, keep=True, level=5): """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`. `level` is compression level: 0 is fastest but larger, 8 is slightly smaller but much slower. """ flac_path = _getFlacPath() wav_files = [] path = pathToString(path) 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 wavname in wav_files: flacfile = wavname.replace('.wav', '.flac') flac_cmd = [flac_path, "-%d" % level, "-f", "--totally-silent", "-o", flacfile, wavname] _junk, 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') _junk, se = core.shellCall(flac_cmd, stderr=True) if se: logging.error(se) if not keep: os.unlink(wavname) flac_files.append(flacfile) if len(wav_files) == 1: return flac_files[0] else: return flac_files
def _detect_rev(): """ Detects revision control system. Recognizes: git, hg """ revs = ["git", "hg"] for rev in revs: try: out, err = core.shellCall(rev + " status", stderr=True) except: # revision control is not installed pass else: if err[:5] not in ["abort", "fatal"]: return rev
def _detect_rev(): """ Detects revision control system. Recognizes: git, hg """ revs = ['git', 'hg'] for rev in revs: try: out, err = core.shellCall(rev + ' status', stderr=True) except: # revision control is not installed pass else: if err[:5] not in ['abort', 'fatal']: return rev
def _getFlacPath(): """Return a path to flac binary. Log flac version (if flac was found). """ global FLAC_PATH if FLAC_PATH is None: if prefs.general['flac']: FLAC_PATH = prefs.general['flac'] else: FLAC_PATH = 'flac' try: version = core.shellCall([FLAC_PATH, '-v'], stderr=True) except: msg = "flac not installed (or wrong path in prefs); download from https://xiph.org/flac/download.html" logging.error(msg) raise MicrophoneError(msg) logging.info('Using ' + ' '.join(version)) return FLAC_PATH
def _getUserNameUID(): """Return user name, UID. UID values can be used to infer admin-level: -1=undefined, 0=full admin/root, >499=assume non-admin/root (>999 on debian-based) :Author: - 2010 written by Jeremy Gray """ user = os.environ.get('USER', None) or os.environ.get('USERNAME', None) if not user: return 'undefined', '-1' if sys.platform not in ['win32']: uid = shellCall('id -u') else: uid = '1000' if haveCtypes and ctypes.windll.shell32.IsUserAnAdmin(): uid = '0' return str(user), int(uid)
def test_Run_FastStroopPsyExp(self): # start from a psyexp file, loadXML, execute, get keypresses from a emulator thread pytest.skip() # test is stalling, hangs up before any text is displayed if sys.platform.startswith("linux"): pytest.skip("response emulation thread not working on linux yet") expfile = path.join(self.exp.prefsPaths["tests"], "data", "ghost_stroop.psyexp") f = codecs.open(file, "r", "utf-8") text = f.read() f.close() # copy conditions file to tmp_dir shutil.copyfile( os.path.join(self.exp.prefsPaths["tests"], "data", "ghost_trialTypes.xlsx"), os.path.join(self.tmp_dir, "ghost_trialTypes.xlsx"), ) # edit the file, to have a consistent font: text = text.replace("'Arial'", "'" + tests.utils.TESTS_FONT + "'") # text = text.replace("Arial",tests.utils.TESTS_FONT) # fails expfile = path.join(self.tmp_dir, "ghost_stroop.psyexp") f = codecs.open(expfile, "w", "utf-8") f.write(text) f.close() self.exp.loadFromXML(expfile) # reload the edited file lastrun = path.join(self.tmp_dir, "ghost_stroop_lastrun.py") script = self.exp.writeScript(expPath=file) # reposition its window out from under splashscreen (can't do easily from .psyexp): text = script.getvalue().replace("fullscr=False,", "pos=(40,40), fullscr=False,") f = codecs.open(lastrun, "w", "utf-8") f.write(text) f.close() # run: stdout, stderr = core.shellCall("python " + lastrun, stderr=True) assert not len(stderr), stderr # print stderr if it's greater than zero
def testRun_FastStroopPsyExp(self): # start from a psyexp file, loadXML, execute, get keypresses from a emulator thread if sys.platform.startswith('linux'): raise nose.plugins.skip.SkipTest("response emulation thread not working on linux yet") os.chdir(self.tmp_dir) file = path.join(exp.prefsPaths['tests'], 'data', 'ghost_stroop.psyexp') f = codecs.open(file, 'r', 'utf-8') text = f.read() f.close() # copy conditions file to tmp_dir shutil.copyfile(os.path.join(self.exp.prefsPaths['tests'], 'data', 'ghost_trialTypes.xlsx'), os.path.join(self.tmp_dir,'ghost_trialTypes.xlsx')) # edit the file, to have a consistent font: text = text.replace("'Arial'","'"+utils.TESTS_FONT+"'") #text = text.replace("Arial",utils.TESTS_FONT) # fails file = path.join(self.tmp_dir, 'ghost_stroop.psyexp') f = codecs.open(file, 'w', 'utf-8') f.write(text) f.close() exp.loadFromXML(file) # reload the edited file lastrun = path.join(self.tmp_dir, 'ghost_stroop_lastrun.py') script = exp.writeScript(expPath=lastrun) # reposition its window out from under splashscreen (can't do easily from .syexp): text = script.getvalue().replace('fullscr=False,','pos=(40,40), fullscr=False,') f = codecs.open(lastrun, 'w', 'utf-8') f.write(text) f.close() # run: stdout, stderr = shellCall('python '+lastrun, stderr=True) if len(stderr): print stderr assert not len(stderr) # NB: "captured stdout" is the stderr from subprocess
def _getFlacPath(path=None): """Return a path to flac binary. Log flac version (if flac was found). """ global FLAC_PATH if FLAC_PATH is None: if path: FLAC_PATH = path elif prefs.general["flac"]: FLAC_PATH = prefs.general["flac"] else: FLAC_PATH = "flac" try: version, se = core.shellCall([FLAC_PATH, "-v"], stderr=True) if se: raise MicrophoneError except: msg = "flac not installed (or wrong path in prefs); download from https://xiph.org/flac/download.html" logging.error(msg) raise MicrophoneError(msg) logging.info("Using " + version) return FLAC_PATH
def test_Run_FastStroopPsyExp(self): # start from a psyexp file, loadXML, execute, get keypresses from a emulator thread if sys.platform.startswith('linux'): pytest.skip("response emulation thread not working on linux yet") expfile = path.join(self.exp.prefsPaths['tests'], 'data', 'ghost_stroop.psyexp') with codecs.open(expfile, 'r', encoding='utf-8-sig') as f: text = f.read() # copy conditions file to tmp_dir shutil.copyfile(os.path.join(self.exp.prefsPaths['tests'], 'data', 'ghost_trialTypes.xlsx'), os.path.join(self.tmp_dir,'ghost_trialTypes.xlsx')) # edit the file, to have a consistent font: text = text.replace("'Arial'", "'" + TESTS_FONT +"'") expfile = path.join(self.tmp_dir, 'ghost_stroop.psyexp') with codecs.open(expfile, 'w', encoding='utf-8-sig') as f: f.write(text) self.exp.loadFromXML(expfile) # reload the edited file script = self.exp.writeScript() # reposition its window out from under splashscreen (can't do easily from .psyexp): script = script.replace('fullscr=False,','pos=(40,40), fullscr=False,') # Only log errors. script = script.replace('logging.console.setLevel(logging.WARNING', 'logging.console.setLevel(logging.ERROR') lastrun = path.join(self.tmp_dir, 'ghost_stroop_lastrun.py') with codecs.open(lastrun, 'w', encoding='utf-8-sig') as f: f.write(script) # run: stdout, stderr = core.shellCall([sys.executable, lastrun], stderr=True) assert not stderr
import sys from psychopy.app._psychopyApp import PsychoPyApp, __version__ # fix OS X locale-bug on startup: sets locale to LC_ALL (must be defined!) import psychopy.locale_setup # noqa # NB the PsychoPyApp classes moved to _psychopyApp.py as of version 1.78.00 # to allow for better upgrading possibilities from the mac app bundle. this # file now used solely as a launcher for the app, not as the app itself. if __name__ == '__main__': if '-x' in sys.argv: # run a .py script from the command line using StandAlone python targetScript = sys.argv[sys.argv.index('-x') + 1] from psychopy import core import os core.shellCall([sys.executable, os.path.abspath(targetScript)]) sys.exit() if '-v' in sys.argv or '--version' in sys.argv: info = 'PsychoPy2, version %s (c)Jonathan Peirce 2015, GNU GPL license' print(info % __version__) sys.exit() if '-h' in sys.argv or '--help' in sys.argv: print("""Starts the PsychoPy2 application. Usage: python PsychoPy.py [options] [file] Without options or files provided this starts PsychoPy using prefs to decide on the view(s) to open. If optional [file] is provided action depends on the type of the [file]: Python script 'file.py' -- opens coder
def getRAM(): """Return system's physical RAM & available RAM, in M. Slow on Mac and Linux; fast on Windows. psutils is good but another dep. """ freeRAM = 'unknown' totalRAM = 'unknown' if sys.platform == 'darwin': lines = core.shellCall('vm_stat').splitlines() pageIndex = lines[0].find('page size of ') if pageIndex > -1: pagesize = int(lines[0][pageIndex + len('page size of '):].split()[0]) lineFree = [ln for ln in lines if ln.startswith('Pages free')][0] lineSpec = [ln for ln in lines if ln.startswith('Pages speculative')][0] free = float(lineFree.split()[-1]) spec = float(lineSpec.split()[-1]) freeRAM = int((free + spec) * pagesize / 1048576.) # M total = core.shellCall(['sysctl', 'hw.memsize']).split(':') totalRAM = int(int(total[-1]) / 1048576.) # M elif sys.platform == 'win32': if not haveCtypes: return 'unknown', 'unknown' try: # http://code.activestate.com/recipes/511491/ # modified by Sol Simpson for 64-bit systems (also ok for 32-bit) kernel32 = ctypes.windll.kernel32 class MEMORYSTATUS(ctypes.Structure): _fields_ = [ ('dwLength', DWORD), ('dwMemoryLoad', DWORD), ('dwTotalPhys', DWORDLONG), # ctypes.c_ulonglong for 64-bit ('dwAvailPhys', DWORDLONG), ('dwTotalPageFile', DWORDLONG), ('dwAvailPageFile', DWORDLONG), ('dwTotalVirtual', DWORDLONG), ('dwAvailVirtual', DWORDLONG), ('ullAvailExtendedVirtual', DWORDLONG), ] memoryStatus = MEMORYSTATUS() memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS) kernel32.GlobalMemoryStatusEx(ctypes.byref(memoryStatus)) totalRAM = int(memoryStatus.dwTotalPhys / 1048576.) # M freeRAM = int(memoryStatus.dwAvailPhys / 1048576.) # M except: pass elif sys.platform.startswith('linux'): try: so = core.shellCall('free') lines = so.splitlines() freeRAM = int(int(lines[1].split()[3]) / 1024.) # M totalRAM = int(int(lines[1].split()[1]) / 1024.) except: pass else: # bsd, works on mac too try: total = core.shellCall('sysctl -n hw.memsize') totalRAM = int(int(total) / 1048576.) # not sure how to get available phys mem except: pass return totalRAM, freeRAM
def _setSystemInfo(self): """System info """ # machine name self['systemHostName'] = platform.node() self['systemMemTotalRAM'], self['systemMemFreeRAM'] = getRAM() # locale information: # (None, None) -> str loc = '.'.join([str(x) for x in locale.getlocale()]) if loc == 'None.None': loc = locale.setlocale(locale.LC_ALL, '') # == the locale in use, from OS or user-pref self['systemLocale'] = loc # platform name, etc if sys.platform in ['darwin']: OSXver, _junk, architecture = platform.mac_ver() platInfo = 'darwin ' + OSXver + ' ' + architecture # powerSource = ... elif sys.platform.startswith('linux'): platInfo = 'linux ' + platform.release() # powerSource = ... elif sys.platform in ['win32']: platInfo = 'windowsversion=' + repr(sys.getwindowsversion()) # powerSource = ... else: platInfo = ' [?]' # powerSource = ... self['systemPlatform'] = platInfo # self['systemPowerSource'] = powerSource # count all unique people (user IDs logged in), and find current user # name & UID self['systemUser'], self['systemUserID'] = _getUserNameUID() try: users = shellCall("who -q").splitlines()[0].split() self['systemUsersCount'] = len(set(users)) except Exception: self['systemUsersCount'] = False # when last rebooted? try: lastboot = shellCall("who -b").split() self['systemRebooted'] = ' '.join(lastboot[2:]) except Exception: # windows sysInfo = shellCall('systeminfo').splitlines() lastboot = [line for line in sysInfo if line.startswith( "System Up Time") or line.startswith("System Boot Time")] lastboot += ['[?]'] # put something in the list just in case self['systemRebooted'] = lastboot[0].strip() # R (and r2py) for stats: try: Rver = shellCall(["R", "--version"]) Rversion = Rver.splitlines()[0] if Rversion.startswith('R version'): self['systemRavailable'] = Rversion.strip() try: import rpy2 self['systemRpy2'] = rpy2.__version__ except ImportError: pass except Exception: pass # encryption / security tools: try: vers, se = shellCall('openssl version', stderr=True) if se: vers = str(vers) + se.replace('\n', ' ')[:80] if vers.strip(): self['systemSec.OpenSSLVersion'] = vers except Exception: pass try: so = shellCall(['gpg', '--version']) if so.find('GnuPG') > -1: self['systemSec.GPGVersion'] = so.splitlines()[0] _home = [line.replace('Home:', '').lstrip() for line in so.splitlines() if line.startswith('Home:')] self['systemSec.GPGHome'] = ''.join(_home) except Exception: pass try: import ssl self['systemSec.pythonSSL'] = True except ImportError: self['systemSec.pythonSSL'] = False # pyo for sound: if PY3: import importlib.util if importlib.util.find_spec('pyo') is not None: self['systemPyoVersion'] = '-' else: import imp try: imp.find_module('pyo') self['systemPyoVersion'] = '-' except: pass # try: # travis = bool(str(os.environ.get('TRAVIS')).lower() == 'true') # assert not travis # skip sound-related stuff on travis-ci.org # # import pyo # self['systemPyoVersion'] = '%i.%i.%i' % pyo.getVersion() # try: # # requires pyo svn r1024 or higher: # import psychopy.sound # inp, out = psychopy.sound.get_devices_infos() # for devList in [inp, out]: # for key in devList: # if isinstance(devList[key]['name'], str): # devList[key]['name'] = devList[key]['name'] # self['systemPyo.InputDevices'] = inp # self['systemPyo.OutputDevices'] = out # except AttributeError: # pass # except (AssertionError, ImportError): # pass # flac (free lossless audio codec) for google-speech: flacv = '' if sys.platform == 'win32': flacexe = 'C:\\Program Files\\FLAC\\flac.exe' if os.path.exists(flacexe): flacv = core.shellCall(flacexe + ' --version') else: flac, se = core.shellCall('which flac', stderr=True) if not se and flac and not flac.find('Command not found') > -1: flacv = core.shellCall('flac --version') if flacv: self['systemFlacVersion'] = flacv # detect internet access or fail quickly: # web.setupProxy() & web.testProxy(web.proxies) # can be slow # to fail if there's no connection self['systemHaveInternetAccess'] = web.haveInternetAccess() if not self['systemHaveInternetAccess']: self['systemHaveInternetAccess'] = 'False (proxies not attempted)'
def _setCurrentProcessInfo(self, verbose=False, userProcsDetailed=False): """What other processes are currently active for this user? """ appFlagList = [ # flag these apps if active, case-insensitive match: # web browsers can burn CPU cycles 'Firefox', 'Safari', 'Explorer', 'Netscape', 'Opera', 'Google Chrome', # but also matches iTunesHelper (add to ignore-list) 'Dropbox', 'BitTorrent', 'iTunes', 'mdimport', 'mdworker', 'mds', # can have high CPU # productivity; on mac, MS Office (Word etc) can be launched by # 'LaunchCFMApp' 'Office', 'KeyNote', 'Pages', 'LaunchCFMApp', 'Skype', 'VirtualBox', 'VBoxClient', # virtual machine as host or client 'Parallels', 'Coherence', 'prl_client_app', 'prl_tools_service', 'VMware'] # just a guess appIgnoreList = [ # always ignore these, exact match: 'ps', 'login', '-tcsh', 'bash', 'iTunesHelper'] # assess concurrently active processes owner by the current user: try: # ps = process status, -c to avoid full path (potentially having # spaces) & args, -U for user if sys.platform not in ['win32']: proc = shellCall("ps -c -U " + os.environ['USER']) else: # "tasklist /m" gives modules as well proc, err = shellCall("tasklist", stderr=True) if err: logging.error('tasklist error:', err) # raise systemProcPsu = [] systemProcPsuFlagged = [] systemUserProcFlaggedPID = [] procLines = proc.splitlines() headerLine = procLines.pop(0) # column labels if sys.platform not in ['win32']: try: # columns and column labels can vary across platforms cmd = headerLine.upper().split().index('CMD') except ValueError: cmd = headerLine.upper().split().index('COMMAND') # process id's extracted in case you want to os.kill() them # from psychopy pid = headerLine.upper().split().index('PID') else: # this works for win XP, for output from 'tasklist' procLines.pop(0) # blank procLines.pop(0) # ===== pid = -5 # pid next after command, which can have # command is first, but can have white space, so end up taking # line[0:pid] cmd = 0 for p in procLines: pr = p.split() # info fields for this process if pr[cmd] in appIgnoreList: continue if sys.platform in ['win32']: # allow for spaces in app names # later just count these unless want details systemProcPsu.append([' '.join(pr[cmd:pid]), pr[pid]]) else: systemProcPsu.append([' '.join(pr[cmd:]), pr[pid]]) matchingApp = [ a for a in appFlagList if a.lower() in p.lower()] for app in matchingApp: systemProcPsuFlagged.append([app, pr[pid]]) systemUserProcFlaggedPID.append(pr[pid]) self['systemUserProcCount'] = len(systemProcPsu) self['systemUserProcFlagged'] = systemProcPsuFlagged if verbose and userProcsDetailed: self['systemUserProcCmdPid'] = systemProcPsu self['systemUserProcFlaggedPID'] = systemUserProcFlaggedPID except Exception: if verbose: self['systemUserProcCmdPid'] = None self['systemUserProcFlagged'] = None # CPU speed (will depend on system busy-ness) d = numpy.array(numpy.linspace(0., 1., 1000000)) t0 = core.getTime() numpy.std(d) t = core.getTime() - t0 del d self['systemTimeNumpySD1000000_sec'] = t