How to use the psychopy.core.quit function in psychopy

To help you get started, we’ve selected a few psychopy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github psychopy / psychopy / psychopy / demos / coder / hardware / ioLab_bbox.py View on Github external
To run this demo the ioLab library needs to be installed (it is included with
the Standalone distributions of PsychoPy).

"""

__author__ = 'Jonathan Roberts'

from psychopy import log
#log.console.setLevel(log.CRITICAL)

from psychopy import core, visual, event
try:
   import ioLabs
except RuntimeError, errMsg:
    log.error('Is an ioLabs button-box connected and turned on? (import failed: "'+str(errMsg)+'")')
    core.quit()

import random

def setup_bbox():
    '''Initialize the button box object and disable all buttons and lights.'''

    global usbbox # button box object declared global so the other routines can use it
    usbbox=ioLabs.USBBox()
    usbbox.buttons.enabled = 0x00 #8 bit pattern 0=disabled 1=enabled
    usbbox.port2.state = 0xFF #port2 is the lights on the bbox - 8 bit pattern 0=on 1=off
    
def enableButtons(buttonList=(0,1,2,3,4,5,6,7)):
    '''enable the specified buttons
    the argument should beone of the following:
    None - disable all buttons
    an integer - enable a single buttonList
github isolver / ioHub / iohub / examples / psychopyIntegrationTest / run.py View on Github external
# You can use this to determine of 'off' the wait period was from the 
# requested wait time. It should be sub msec in general (at least when 
# tested on Windows with an i7 CPU). Please let us know if you find differently.
requested_delay=1.5
actual_delay=io.wait(requested_delay)

print "Delay requested %.6f, actual delay %.6f, Diff: %.6f"%(requested_delay,
                                                             actual_delay,
                                                             actual_delay-requested_delay)

# Close neccessary files / objects:
#
# Be sure to shut down the ioHub Server:
io.quit()
# And the psychopy system:
core.quit()
github psychopy / psychopy / psychopy / demos / coder / misc / captureFrames.py View on Github external
myStim.draw()
    # you can either read from the back buffer BEFORE win.flip() or
    # from the front buffer just AFTER the flip. The former has the
    # advantage that it won't be affected by other windows whereas
    # latter can be.
    win.getMovieFrame(buffer='back')
    win.flip()

# save the movie in the format of your choice
win.saveMovieFrames('frame.png', clearFrames=False)
win.saveMovieFrames('myMovie.gif', clearFrames=False)
win.saveMovieFrames('myMovie.mp4', clearFrames=False)
win.saveMovieFrames('myMovie.mov', clearFrames=False)

win.close()
core.quit()
github psychopy / psychopy / psychopy / demos / coder / experiment control / JND_staircase_exp.py View on Github external
from psychopy import core, visual, gui, data, misc, event
import time, numpy

try:#try to get a previous parameters file
    expInfo = misc.fromFile('lastParams.pickle')
except:#if not there then use a default set
    expInfo = {'observer':'jwp', 'refOrientation':0}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='simple JND Exp', fixed=['date'])
if dlg.OK:
    misc.toFile('lastParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

#make a text file to save data
fileName = expInfo['observer'] + dateStr
dataFile = open(fileName+'.txt', 'w')
dataFile.write('targetSide	oriIncrement	correct\n')

#create window and stimuli
globalClock = core.Clock()#to keep track of time
trialClock = core.Clock()#to keep track of time
win = visual.Window([800,600],allowGUI=False, monitor='testMonitor', units='deg')
foil = visual.PatchStim(win, sf=1, size=4, mask='gauss', ori=expInfo['refOrientation'])
target = visual.PatchStim(win, sf=1,  size=4, mask='gauss', ori=expInfo['refOrientation'])
fixation = visual.PatchStim(win, color='black', tex=None, mask='circle',size=0.2)
message1 = visual.TextStim(win, pos=[0,+3],text='Hit a key when ready.')
message2 = visual.TextStim(win, pos=[0,-3], text="Then press left or right to identify the %.1fdegree probe." %(expInfo['refOrientation']))
github lindeloev / psychopy-course / ppc_template_version2.py View on Github external
def ask(Q):
    """ Ask subject something. Shows question and response options and
    returns answer (keypress) and reaction time"""
    # Show text and fixation cross
    message.setText(Q['text'])
    message.draw()
    fix.draw()          # Fixation cross also drawn with question. It's more relaxing for the subject.
    win.flip()          # Show the stimuli on next monitor update and ...
    clock.reset()  # immediately reset the clock. Reaction time is relative to text onset.

    # Halt everything and wait for responses matching the keys given in the Q object.
    key, rt = event.waitKeys(keyList=Q['allowedKeys'] + quitKeys, timeStamped=clock)[0]
    if key in quitKeys: core.quit()     # Quit everything if quit-key was pressed
    return key, rt    # return (keycode, response_time)
github isolver / ioHub / util / experiment / psychopyIOHubRuntime.py View on Github external
def _close(self):
        """
        Close the experiment runtime and the ioHub server process.
        """
        # terminate the ioServer
        if self.hub:
            self.hub._shutDownServer()
        # terminate psychopy
        core.quit()
github isolver / ioHub / examples / simpleScriptOnly / run.py View on Github external
# likely causing a mutlipacket getEvents() since we have not cleared the
# event buffer or retrieved events from anything but the keyboard since
# the start.
stime = Computer.currentSec()
events=io.getEvents()
etime=Computer.currentSec()
print 'event count: ', len(events),' delay (msec): ',(etime-stime)*1000.0

# close neccessary files / objects, 'disable high priority.
Computer.disableHighPriority()
 
psychoWindow.close()

# be sure to shutdown your ioHub server!
io.quit()
core.quit()
### End of experiment logic
github psychopy / psychopy / psychopy / visual.py View on Github external
rad=makeRadialMatrix(res)
        sigma = 1/3.0;
        intensity = numpy.exp( -rad**2.0 / (2.0*sigma**2.0) )*2-1 #3sd.s by the edge of the stimulus
        fromFile=0
    elif tex is "radRamp":#a radial ramp
        rad=makeRadialMatrix(res)
        intensity = 1-2*rad
        intensity = numpy.where(rad<-1, intensity, -1)#clip off the corners (circular)
        fromFile=0
    else:#might be a filename of an image
        try:
            im = Image.open(tex)
            im = im.transpose(Image.FLIP_TOP_BOTTOM)
        except:
            log.error("couldn't load tex...%s" %(tex))
            core.quit()
            raise #so that we quit

        #is it 1D?
        if im.size[0]==1 or im.size[1]==1:
            log.error("Only 2D textures are supported at the moment")
        else:
            maxDim = max(im.size)
            powerOf2 = 2**numpy.ceil(numpy.log2(maxDim))
            if im.size[0]!=powerOf2 or im.size[1]!=powerOf2:
                log.warning("Image '%s' was not a square power-of-two image. Linearly interpolating to be %ix%i" %(tex, powerOf2, powerOf2))
                im.resize([powerOf2,powerOf2],Image.BILINEAR)                    

        #is it Luminance or RGB?
        if im.mode=='L':
            wasLum = True
            intensity= numpy.array(im).astype(numpy.float32)*2/255-1.0 #get to range -1:1
github psychopy / psychopy / psychopy / demos / coder / iohub / serial / pstbox.py View on Github external
#
# Start the experiment.
#

pstbox.clearEvents()
start_time = computer.getTime()

# Display instruction and check if we collected any button events.
# If there is no button press within a 30 s period, quit.
instruction.draw()
win.flip()
while not pstbox.getEvents():
    if core.getTime() - start_time > 30:
        print('Timeout waiting for button event. Exiting...')
        io.quit()
        core.quit()

# Clear the screen.
win.flip()

nreps = 10
RT = np.array([])
button = np.array([])
io.wait(2)

for i in range(nreps):
    print('Trial #', i)

    # Raise process priorities.
    computer.setPriority('high')
    io.setPriority('high')
github psychopy / psychopy / psychopy / sound / backend_pyo.py View on Github external
pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)  # wait for server to boot before starting the sound stream
    pyoSndServer.start()

    # atexit is filo, will call stop then shutdown upon closing
    atexit.register(pyoSndServer.shutdown)
    atexit.register(pyoSndServer.stop)
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if sys.platform == 'darwin' and audioDriver != 'portaudio':
            msg += "; maybe try prefs.general.audioDriver 'portaudio'?"
        logging.error(msg)
        core.quit()
    logging.debug('pyo sound server started')
    logging.flush()