Example #1
0
 def test_soundpyo_array(self):
     """anything using a numpy.array uses pyo.DataTable
     """
     if pyo.getVersion() < (0, 7, 7):
         pytest.xfail()  # pyo leak fixed Oct 2015
     for stim in [440, np.zeros(88200)]:  # np.zeros(8820000) passes, slow
         assert leakage(sound.SoundPyo, stim, secs=2) < THRESHOLD, 'stim = ' + str(stim)
Example #2
0
 def test_soundpyo_array(self):
     """anything using a numpy.array uses pyo.DataTable
     """
     if pyo.getVersion() < (0, 7, 7):
         pytest.xfail()  # pyo leak fixed Oct 2015
     for stim in [440, np.zeros(88200)]:  # np.zeros(8820000) passes, slow
         assert leakage(sound.SoundPyo, stim, secs=2) < THRESHOLD, 'stim = ' + str(stim)
Example #3
0
    def test_soundpyo_file(self):
        """files are handled by pyo.SndFile
        """
        if pyo.getVersion() < (0, 7, 7):
            pytest.xfail()
        from scipy.io import wavfile
        tmp = os.path.join(self.tmp, 'zeros.wav')
        wavfile.write(tmp, 44100, np.zeros(88200))

        assert leakage(sound.SoundPyo, tmp) < THRESHOLD
Example #4
0
    def test_soundpyo_file(self):
        """files are handled by pyo.SndFile
        """
        if pyo.getVersion() < (0, 7, 7):
            pytest.xfail()
        from scipy.io import wavfile
        tmp = os.path.join(self.tmp, 'zeros.wav')
        wavfile.write(tmp, 44100, np.zeros(88200))

        assert leakage(sound.SoundPyo, tmp) < THRESHOLD
Example #5
0
def validateVersions():
    import sys
    from pyo import getVersion
    import wxversion
    if sys.version_info[0] > VERSIONS['python'][0]:
        printMessage("python {}.x must be used to run Pyo Synth from sources".format(VERSIONS['python'][0]), 2)
    if getVersion() != VERSIONS['pyo']:
        printMessage("pyo version installed: {}.{}.{} ; pyo version required {}.{}.{}".format(*getVersion()+VERSIONS['pyo']), 1)
        printMessage("Installed pyo version doesn't match what Pyo Synth uses. Some objects might not be available.", 1)
    if not wxversion.checkInstalled('2.8'):
        printMessage("wxPython version required {}.{}.{}".format(*VERSIONS['wx']), 1)
Example #6
0
print("\nPython info")
print(sys.executable)
print(sys.version)
import numpy
print("numpy", numpy.__version__)
import scipy
print("scipy", scipy.__version__)
import matplotlib
print("matplotlib", matplotlib.__version__)
import pyglet
print("pyglet", pyglet.version)
# pyo is a new dependency, for sound:
try:
    import pyo
    print("pyo", '%i.%i.%i' % pyo.getVersion())
except Exception:
    print('pyo [not installed]')

from psychopy import __version__
print("\nPsychoPy", __version__)

win = visual.Window([100, 100])  # some drivers want a window open first
print("have shaders:", win._haveShaders)
print("\nOpenGL info:")
# get info about the graphics card and drivers
print("vendor:", gl_info.get_vendor())
print("rendering engine:", gl_info.get_renderer())
print("OpenGL version:", gl_info.get_version())
print("(Selected) Extensions:")
extensionsOfInterest = ['GL_ARB_multitexture',
Example #7
0
print sys.version
import numpy

print "numpy", numpy.__version__
import scipy

print "scipy", scipy.__version__
import matplotlib

print "matplotlib", matplotlib.__version__
import pyglet

print "pyglet", pyglet.version
import pyo

print "pyo", ".".join(map(str, pyo.getVersion()))
from psychopy import __version__

print "PsychoPy", __version__

win = visual.Window([100, 100])  # some drivers want a window open first
print "\nOpenGL info:"
# get info about the graphics card and drivers
print "vendor:", gl_info.get_vendor()
print "rendering engine:", gl_info.get_renderer()
print "OpenGL version:", gl_info.get_version()
print "(Selected) Extensions:"
extensionsOfInterest = [
    "GL_ARB_multitexture",
    "GL_EXT_framebuffer_object",
    "GL_ARB_fragment_program",
Example #8
0
 def _setSystemInfo(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()
     
     # R (and r2py) for stats:
     try:
         Rver,err = shellCall("R --version",stderr=True)
         Rversion = Rver.splitlines()[0]
         if Rversion.startswith('R version'):
             self['systemRavailable'] = Rversion.strip()
         try:
             import rpy2
             self['systemRpy2'] = rpy2.__version__
         except:
             pass
     except:
         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:
         pass
     try:
         so, se = shellCall('gpg --version', stderr=True)
         if so.find('GnuPG') > -1:
             self['systemSec.GPGVersion'] = so.splitlines()[0]
             self['systemSec.GPGHome'] = ''.join([line.replace('Home:','').lstrip()
                                                 for line in so.splitlines()
                                                 if line.startswith('Home:')])
     except:
         pass
     try:
         import ssl
         self['systemSec.pythonSSL'] = True
     except ImportError:
         self['systemSec.pythonSSL'] = False
     
     # pyo for sound:
     try:
         import pyo
         self['systemPyoVersion'] = '.'.join(map(str, pyo.getVersion()))
     except:
         pass
Example #9
0
    def _setSystemInfo(self):
        """system info"""
        # system encoding
        osEncoding=sys.getfilesystemencoding()

        # machine name
        self['systemHostName'] = platform.node()

        self['systemMemTotalRAM'], self['systemMemFreeRAM'] = getRAM()

        # locale information:
        loc = '.'.join([str(x) for x in locale.getlocale()])  # (None, None) -> str
        if loc == 'None.None':
            loc = locale.setlocale(locale.LC_ALL, '')
        self['systemLocale'] = loc  # == the locale in use, from OS or user-pref

        # 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:
            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.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:
            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:
            pass
        try:
            so = shellCall(['gpg', '--version'])
            if so.find('GnuPG') > -1:
                self['systemSec.GPGVersion'] = so.splitlines()[0]
                self['systemSec.GPGHome'] = ''.join([line.replace('Home:', '').lstrip()
                                                    for line in so.splitlines()
                                                    if line.startswith('Home:')])
        except:
            pass
        try:
            import ssl
            self['systemSec.pythonSSL'] = True
        except ImportError:
            self['systemSec.pythonSSL'] = False

        # pyo for sound:
        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:
                inp, out = pyo.pa_get_devices_infos()
                for devList in [inp, out]:
                    for key in devList.keys():
                        if isinstance(devList[key]['name'], str):
                            devList[key]['name'] = devList[key]['name'].decode(osEncoding)
                self['systemPyo.InputDevices'] = inp
                self['systemPyo.OutputDevices'] = out
            except AttributeError:
                pass
        except AssertionError, ImportError:
            pass
Example #10
0
def init(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    global pyo
    try:
        assert pyo
    except NameError:  # pragma: no cover
        import pyo
        # can be needed for microphone.switchOn(), which calls init even
        # if audioLib is something else

    # subclass the pyo.Server so that we can insert a __del__ function that
    # shuts it down skip coverage since the class is never used if we have
    # a recent version of pyo

    class _Server(pyo.Server):  # pragma: no cover
        # make libs class variables so they don't get deleted first
        core = core
        logging = logging

        def __del__(self):
            self.stop()
            # make sure enough time passes for the server to shutdown
            self.core.wait(0.5)
            self.shutdown()
            # make sure enough time passes for the server to shutdown
            self.core.wait(0.5)
            # this may never get printed
            self.logging.debug('pyo sound server shutdown')

    if '.'.join(map(str, pyo.getVersion())) < '0.6.4':
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if 'pyoSndServer' in globals() and hasattr(pyoSndServer, 'shutdown'):
        pyoSndServer.stop()
        # make sure enough time passes for the server to shutdown
        core.wait(0.5)
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate,
                            nchnls=maxChnls,
                            buffersize=buffer,
                            audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform == 'win32':
            # check for output device/driver
            devNames, devIDs = pyo.pa_get_output_devices()
            audioDriver, outputID = _bestDriver(devNames, devIDs)
            if outputID is None:
                # using the default output because we didn't find the one(s)
                # requested
                audioDriver = 'Windows Default Output'
                outputID = pyo.pa_get_default_output()
            if outputID is not None:
                logging.info('Using sound driver: %s (ID=%i)' %
                             (audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(outputID)
            else:
                logging.warning(
                    'No audio outputs found (no speakers connected?')
                return -1
            # check for valid input (mic)
            # If no input device is available, devNames and devIDs are empty
            # lists.
            devNames, devIDs = pyo.pa_get_input_devices()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            # Input devices were found, but requested devices were not found
            if len(devIDs) > 0 and inputID is None:
                defaultID = pyo.pa_get_default_input()
                if defaultID is not None and defaultID != -1:
                    # default input is found
                    # use the default input because we didn't find the one(s)
                    # requested
                    audioInputName = 'Windows Default Input'
                    inputID = defaultID
                else:
                    # default input is not available
                    inputID = None
            if inputID is not None:
                msg = 'Using sound-input driver: %s (ID=%i)'
                logging.info(msg % (audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                maxInputChnls = 0
                duplex = False
        # for other platforms set duplex to True (if microphone is available)
        else:
            audioDriver = prefs.general['audioDriver'][0]
            maxInputChnls = pyo.pa_get_input_max_channels(
                pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(
                pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:  # pragma: no cover
            msg = ('%s.init could not find microphone hardware; '
                   'recording not available')
            logging.warning(msg % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:  # pragma: no cover
            msg = ('%s.init could not find speaker hardware; '
                   'sound not available')
            logging.error(msg % __name__)
            return -1

        # create the instance of the server:
        if platform in ['darwin', 'linux2']:
            # for mac/linux we set the backend using the server audio param
            pyoSndServer = Server(sr=rate,
                                  nchnls=maxChnls,
                                  buffersize=buffer,
                                  audio=audioDriver)
        else:
            # with others we just use portaudio and then set the OutputDevice
            # below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform == 'win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID is not None:
                pyoSndServer.setInputDevice(inputID)
        # do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)  # wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if 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()
Example #11
0
    def getInfoText(self):
        """Get system information text."""
        outputText = ""  # text to return

        # show the PsychoPy version
        from psychopy import __version__
        outputText += self.getLine("PsychoPy", __version__)

        # get system paths
        outputText += self.getLine("\nPaths to files on the system:")
        for key in ['userPrefsFile', 'appDataFile', 'demos', 'appFile']:
            outputText += self.getLine(
                "    %s: %s" % (key, preferences.prefs.paths[key]))

        # system information such as OS, CPU and memory
        outputText += self.getLine("\nSystem Info:")
        outputText += self.getLine(
            ' '*4, 'Operating System: {}'.format(platform.platform()))
        outputText += self.getLine(
            ' ' * 4, 'Processor: {}'.format(platform.processor()))

        # requires psutil
        try:
            import psutil
            outputText += self.getLine(
                ' ' * 4, 'CPU freq (MHz): {}'.format(psutil.cpu_freq().max))
            outputText += self.getLine(
                ' ' * 4, 'CPU cores: {} (physical), {} (logical)'.format(
                    psutil.cpu_count(False), psutil.cpu_count()))
            outputText += self.getLine(
                ' ' * 4, 'Installed memory: {} (Total), {} (Available)'.format(
                    *psutil.virtual_memory()))
        except ImportError:
            outputText += self.getLine(' ' * 4, 'CPU freq (MHz): N/A')
            outputText += self.getLine(
                ' ' * 4, 'CPU cores: {} (logical)'.format(os.cpu_count()))
            outputText += self.getLine(' ' * 4, 'Installed memory: N/A')

        # if on MacOS
        if sys.platform == 'darwin':
            OSXver, junk, architecture = platform.mac_ver()
            outputText += self.getLine(
                ' ' * 4, "macOS %s running on %s" % (OSXver, architecture))

        # Python information
        outputText += self.getLine("\nPython info:")
        outputText += self.getLine(' '*4, 'Executable path:', sys.executable)
        outputText += self.getLine(' '*4, 'Version:', sys.version)
        outputText += self.getLine(' ' * 4, '(Selected) Installed Packages:')
        import numpy
        outputText += self.getLine(' '*8, "numpy ({})".format(
            numpy.__version__))
        import scipy
        outputText += self.getLine(' '*8, "scipy ({})".format(
            scipy.__version__))
        import matplotlib
        outputText += self.getLine(' '*8, "matplotlib ({})".format(
            matplotlib.__version__))
        import pyglet
        outputText += self.getLine(' '*8, "pyglet ({})".format(pyglet.version))
        try:
            import glfw
            outputText += self.getLine(' '*8, "PyGLFW ({})".format(
                glfw.__version__))
        except Exception:
            outputText += self.getLine(' '*8, 'PyGLFW [not installed]')

        # sound related
        try:
            import pyo
            outputText += self.getLine(
                ' '*8, "pyo", ('%i.%i.%i' % pyo.getVersion()))
        except Exception:
            outputText += self.getLine(' '*8, 'pyo [not installed]')
        try:
            import psychtoolbox
            outputText += self.getLine(' '*8, "psychtoolbox ({})".format(
                psychtoolbox._version.__version__))
        except Exception:
            outputText += self.getLine(' '*8, 'psychtoolbox [not installed]')

        # wxpython version
        try:
            import wx
            outputText += self.getLine(' '*8, "wxPython ({})".format(
                wx.__version__))
        except Exception:
            outputText += self.getLine(' '*8, 'wxPython [not installed]')

        # get OpenGL details
        win = visual.Window([100, 100])  # some drivers want a window open first

        outputText += self.getLine("\nOpenGL Info:")
        # # get info about the graphics card and drivers
        outputText += self.getLine(
            ' '*4, "Vendor:", gl_info.get_vendor())
        outputText += self.getLine(
            ' '*4, "Rendering engine:", gl_info.get_renderer())
        outputText += self.getLine(
            ' '*4, "OpenGL version:", gl_info.get_version())
        outputText += self.getLine(
            ' '*4, "Shaders supported: ", win._haveShaders)

        # get opengl extensions
        outputText += self.getLine(' '*4, "(Selected) Extensions:")
        extensionsOfInterest = [
            'GL_ARB_multitexture',
            'GL_EXT_framebuffer_object',
            'GL_ARB_fragment_program',
            'GL_ARB_shader_objects',
            'GL_ARB_vertex_shader',
            'GL_ARB_texture_non_power_of_two',
            'GL_ARB_texture_float',
            'GL_STEREO']

        for ext in extensionsOfInterest:
            outputText += self.getLine(
                ' '*8, ext + ':', bool(gl_info.have_extension(ext)))

        # also determine nVertices that can be used in vertex arrays
        maxVerts = GLint()
        glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
        outputText += self.getLine(
            ' '*4, 'max vertices in vertex array:', maxVerts.value)

        win.close()

        return outputText
Example #12
0
def init(lib=None,
         samplerate=22050,
         channels=2,
         buffersize=2048,
         reinit=False):
    """ (Re-)Initialize sound subsystem """
    # Note on buffer size: Too high values cause crackling during fade, too low
    # values cause choppy playback of ogg files when using pyo (good value for
    # pyo is >= 2048)
    global _initialized, _lib, _lib_version, _server, pyglet, pyo, sdl, wx
    if _initialized and not reinit:
        # To re-initialize, explicitly set reinit to True
        return
    # Select the audio library we're going to use.
    # User choice or SDL > pyglet > pyo > wx
    if not lib:
        if sys.platform in ("darwin", "win32"):
            # Mac OS X, Windows
            libs = ("pyglet", "SDL", "pyo", "wx")
        else:
            # Linux
            libs = ("SDL", "pyglet", "pyo", "wx")
        for lib in libs:
            try:
                return init(lib, samplerate, channels, buffersize, reinit)
            except Exception as exception:
                pass
        raise exception
    elif lib == "pyglet":
        if not getattr(sys, "frozen", False):
            # Use included pyglet
            lib_dir = os.path.join(os.path.dirname(__file__), "lib")
            if not lib_dir in sys.path:
                sys.path.insert(0, lib_dir)
        try:
            import pyglet
            version = []
            for item in pyglet.version.split("."):
                try:
                    version.append(int(item))
                except ValueError:
                    version.append(item)
            if version < [1, 2, 2]:
                raise ImportError("pyglet version %s is too old" %
                                  pyglet.version)
            _lib = "pyglet"
        except ImportError:
            _lib = None
        else:
            # Work around localization preventing fallback to RIFFSourceLoader
            pyglet.lib.LibraryLoader.darwin_not_found_error = ""
            pyglet.lib.LibraryLoader.linux_not_found_error = ""
            # Set audio driver preference
            pyglet.options["audio"] = ("pulse", "openal", "directsound",
                                       "silent")
            _server = pyglet.media
            _lib_version = pyglet.version
    elif lib == "pyo":
        try:
            import pyo
            _lib = "pyo"
        except ImportError:
            _lib = None
        else:
            if isinstance(_server, pyo.Server):
                _server.reinit(sr=samplerate,
                               nchnls=channels,
                               buffersize=buffersize,
                               duplex=0)
            else:
                _server = pyo.Server(sr=samplerate,
                                     nchnls=channels,
                                     buffersize=buffersize,
                                     duplex=0,
                                     winhost="asio").boot()
                _server.start()
                _lib_version = ".".join(str(v) for v in pyo.getVersion())
    elif lib == "SDL":
        SDL_INIT_AUDIO = 16
        AUDIO_S16LSB = 0x8010
        AUDIO_S16MSB = 0x9010
        if sys.byteorder == "little":
            MIX_DEFAULT_FORMAT = AUDIO_S16LSB
        else:
            MIX_DEFAULT_FORMAT = AUDIO_S16MSB
        if sys.platform == "win32":
            pth = getenvu("PATH")
            libpth = os.path.join(pydir, "lib")
            if not pth.startswith(libpth + os.pathsep):
                pth = libpth + os.pathsep + pth
                os.environ["PATH"] = safe_str(pth)
        elif sys.platform == "darwin":
            x_framework_pth = os.getenv("X_DYLD_FALLBACK_FRAMEWORK_PATH")
            if x_framework_pth:
                framework_pth = os.getenv("DYLD_FALLBACK_FRAMEWORK_PATH")
                if framework_pth:
                    x_framework_pth = os.pathsep.join(
                        [x_framework_pth, framework_pth])
                os.environ["DYLD_FALLBACK_FRAMEWORK_PATH"] = x_framework_pth
        for libname in ("SDL2", "SDL2_mixer", "SDL", "SDL_mixer"):
            handle = None
            if sys.platform in ("darwin", "win32"):
                libfn = ctypes.util.find_library(libname)
            if sys.platform == "win32":
                if libfn and win32api:
                    # Support for unicode paths
                    libfn = safe_unicode(libfn)
                    try:
                        handle = win32api.LoadLibrary(libfn)
                    except pywintypes.error:
                        pass
            elif sys.platform != "darwin":
                # Hard-code lib names for Linux
                libfn = "lib" + libname
                if libname.startswith("SDL2"):
                    # SDL 2.0
                    libfn += "-2.0.so.0"
                else:
                    # SDL 1.2
                    libfn += "-1.2.so.0"
            dll = dlopen(libfn, handle=handle)
            if dll:
                safe_print("%s:" % libname, libfn)
            if libname.endswith("_mixer"):
                if not dll:
                    continue
                if not sdl:
                    raise RuntimeError("SDL library not loaded")
                sdl.SDL_RWFromFile.restype = POINTER(SDL_RWops)
                _server = dll
                _server.Mix_OpenAudio.argtypes = [
                    c_int, c_uint16, c_int, c_int
                ]
                _server.Mix_LoadWAV_RW.argtypes = [POINTER(SDL_RWops), c_int]
                _server.Mix_LoadWAV_RW.restype = POINTER(Mix_Chunk)
                _server.Mix_PlayChannelTimed.argtypes = [
                    c_int, POINTER(Mix_Chunk), c_int, c_int
                ]
                _server.Mix_VolumeChunk.argtypes = [POINTER(Mix_Chunk), c_int]
                if _initialized:
                    _server.Mix_Quit()
                    sdl.SDL_Quit()
                sdl.SDL_Init(SDL_INIT_AUDIO)
                _server.Mix_OpenAudio(samplerate, MIX_DEFAULT_FORMAT, channels,
                                      buffersize)
                _lib = "SDL"
                if libname.startswith("SDL2"):
                    _lib_version = "2.0"
                else:
                    _lib_version = "1.2"
                break
            else:
                sdl = dll
                _server = None
    elif lib == "wx":
        try:
            import wx
            _lib = "wx"
        except ImportError:
            _lib = None
        else:
            _server = wx
            _lib_version = wx.__version__
    if not _lib:
        raise RuntimeError("No audio library available")
    _initialized = True
    return _server
Example #13
0
print "\nSystem info:"
print platform.platform()
if sys.platform=='darwin':
    OSXver, junk, architecture = platform.mac_ver()
    print "OS X %s running on %s" %(OSXver, architecture)

print "\nPython info"
print sys.executable
print sys.version
import numpy; print "numpy", numpy.__version__
import scipy; print "scipy", scipy.__version__
import matplotlib; print "matplotlib", matplotlib.__version__
import pyglet; print "pyglet", pyglet.version
# pyo is a new dependency, for sound:
try: import pyo; print "pyo", '%i.%i.%i' % pyo.getVersion()
except: print 'pyo [not installed]'

from psychopy import __version__
print "\nPsychoPy", __version__

win = visual.Window([100,100])#some drivers want a window open first
print "have shaders:", win._haveShaders
print "\nOpenGL info:"
#get info about the graphics card and drivers
print "vendor:", gl_info.get_vendor()
print "rendering engine:", gl_info.get_renderer()
print "OpenGL version:", gl_info.get_version()
print "(Selected) Extensions:"
extensionsOfInterest=['GL_ARB_multitexture', 
    'GL_EXT_framebuffer_object','GL_ARB_fragment_program',
Example #14
0
    def _setSystemInfo(self):
        """system info"""
        # system encoding
        osEncoding = sys.getfilesystemencoding()

        # machine name
        self['systemHostName'] = platform.node()

        self['systemMemTotalRAM'], self['systemMemFreeRAM'] = getRAM()

        # locale information:
        loc = '.'.join([str(x)
                        for x in locale.getlocale()])  # (None, None) -> str
        if loc == 'None.None':
            loc = locale.setlocale(locale.LC_ALL, '')
        self[
            'systemLocale'] = loc  # == the locale in use, from OS or user-pref

        # 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:
            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.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:
            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:
            pass
        try:
            so = shellCall(['gpg', '--version'])
            if so.find('GnuPG') > -1:
                self['systemSec.GPGVersion'] = so.splitlines()[0]
                self['systemSec.GPGHome'] = ''.join([
                    line.replace('Home:', '').lstrip()
                    for line in so.splitlines() if line.startswith('Home:')
                ])
        except:
            pass
        try:
            import ssl
            self['systemSec.pythonSSL'] = True
        except ImportError:
            self['systemSec.pythonSSL'] = False

        # pyo for sound:
        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:
                inp, out = pyo.pa_get_devices_infos()
                for devList in [inp, out]:
                    for key in devList.keys():
                        if isinstance(devList[key]['name'], str):
                            devList[key]['name'] = devList[key]['name'].decode(
                                osEncoding)
                self['systemPyo.InputDevices'] = inp
                self['systemPyo.OutputDevices'] = out
            except AttributeError:
                pass
        except AssertionError, ImportError:
            pass
Example #15
0
def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    global pyo
    try:
        assert pyo
    except NameError:  # pragma: no cover
        import pyo  # microphone.switchOn() calls initPyo even if audioLib is something else
    #subclass the pyo.Server so that we can insert a __del__ function that shuts it down
    # skip coverage since the class is never used if we have a recent version of pyo
    class _Server(pyo.Server):  # pragma: no cover
        core=core #make libs class variables so they don't get deleted first
        logging=logging
        def __del__(self):
            self.stop()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.shutdown()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.logging.debug('pyo sound server shutdown')#this may never get printed
    if '.'.join(map(str, pyo.getVersion())) < '0.6.4':
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if 'pyoSndServer' in globals() and hasattr(pyoSndServer,'shutdown'):
        pyoSndServer.stop()
        core.wait(0.5)#make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform=='win32':
            #check for output device/driver
            devNames, devIDs=pyo.pa_get_output_devices()
            audioDriver,outputID=_bestDriver(devNames, devIDs)
            if outputID is None:
                audioDriver = 'Windows Default Output' #using the default output because we didn't find the one(s) requested
                outputID = pyo.pa_get_default_output()
            if outputID is not None:
                logging.info('Using sound driver: %s (ID=%i)' %(audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(outputID)
            else:
                logging.warning('No audio outputs found (no speakers connected?')
                return -1
            #check for valid input (mic)
            devNames, devIDs = pyo.pa_get_input_devices()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            if inputID is None:
                audioInputName = 'Windows Default Input' #using the default input because we didn't find the one(s) requested
                inputID = pyo.pa_get_default_input()
            if inputID is not None:
                logging.info('Using sound-input driver: %s (ID=%i)' %(audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                maxInputChnls = 0
                duplex=False
        else:#for other platforms set duplex to True (if microphone is available)
            audioDriver = prefs.general['audioDriver'][0]
            maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:  # pragma: no cover
            logging.warning('%s.initPyo could not find microphone hardware; recording not available' % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:  # pragma: no cover
            logging.error('%s.initPyo could not find speaker hardware; sound not available' % __name__)
            return -1

        # create the instance of the server:
        if platform in ['darwin', 'linux2']:
            #for mac/linux we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        else:
            #with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform=='win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID is not None:
                pyoSndServer.setInputDevice(inputID)
        #do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)#wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if 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()
Example #16
0
def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    if not 'pyo' in locals():
        import pyo  # microphone.switchOn() calls initPyo even if audioLib is something else
    #subclass the pyo.Server so that we can insert a __del__ function that shuts it down
    class _Server(pyo.Server):
        core=core #make libs class variables so they don't get deleted first
        logging=logging
        def __del__(self):
            self.stop()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.shutdown()
            self.core.wait(0.5)#make sure enough time passes for the server to shutdown
            self.logging.debug('pyo sound server shutdown')#this may never get printed
    if '.'.join(map(str, pyo.getVersion())) < '0.6.4':
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if globals().has_key('pyoSndServer') and hasattr(pyoSndServer,'shutdown'):
        pyoSndServer.stop()
        core.wait(0.5)#make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform=='win32':
            #check for output device/driver
            devNames, devIDs=pyo.pa_get_output_devices()
            audioDriver,outputID=_bestDriver(devNames, devIDs)
            if outputID:
                logging.info('Using sound driver: %s (ID=%i)' %(audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(outputID)
            else:
                logging.warning('No audio outputs found (no speakers connected?')
                return -1
            #check for valid input (mic)
            devNames, devIDs = pyo.pa_get_input_devices()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            if inputID is not None:
                logging.info('Using sound-input driver: %s (ID=%i)' %(audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                duplex=False
        else:#for other platforms set duplex to True (if microphone is available)
            audioDriver = prefs.general['audioDriver'][0]
            maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:
            logging.warning('%s.initPyo could not find microphone hardware; recording not available' % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:
            logging.error('%s.initPyo could not find speaker hardware; sound not available' % __name__)
            return -1

        # create the instance of the server:
        if platform=='darwin':
            #for mac we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        else:
            #with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform=='win32':
            pyoSndServer.setOutputDevice(outputID)
            if inputID:
                pyoSndServer.setInputDevice(inputID)
        #do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)#wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if 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()
Example #17
0
    def _setSystemInfo(self):
        """system info"""
        # system encoding
        osEncoding=sys.getfilesystemencoding()

        # machine name
        self['systemHostName'] = platform.node()

        self['systemMemTotalRAM'], self['systemMemFreeRAM'] = getRAM()

        # locale information:
        loc = '.'.join([str(x) for x in locale.getlocale()])  # (None, None) -> str
        if loc == 'None.None':
            loc = locale.setlocale(locale.LC_ALL, '')
        self['systemLocale'] = loc  # == the locale in use, from OS or user-pref

        # 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:
            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.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:
            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:
            pass
        try:
            so = shellCall(['gpg', '--version'])
            if so.find('GnuPG') > -1:
                self['systemSec.GPGVersion'] = so.splitlines()[0]
                self['systemSec.GPGHome'] = ''.join([line.replace('Home:', '').lstrip()
                                                    for line in so.splitlines()
                                                    if line.startswith('Home:')])
        except:
            pass
        try:
            import ssl
            self['systemSec.pythonSSL'] = True
        except ImportError:
            self['systemSec.pythonSSL'] = False

        # pyo for sound:
        try:
            import pyo
            self['systemPyoVersion'] = '%i.%i.%i' % pyo.getVersion()
            try:
                # requires pyo svn r1024 or higher:
                inp, out = pyo.pa_get_devices_infos()
                for devList in [inp, out]:
                    for key in devList.keys():
                        if isinstance(devList[key]['name'], str):
                            devList[key]['name'] = devList[key]['name'].decode(osEncoding)
                self['systemPyo.InputDevices'] = inp
                self['systemPyo.OutputDevices'] = out
            except AttributeError:
                pass
        except 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 take a long time to fail if there's no connection
        self['systemHaveInternetAccess'] = web.haveInternetAccess()
        if not self['systemHaveInternetAccess']:
            self['systemHaveInternetAccess'] = 'False (proxies not attempted)'
Example #18
0
def initPyo(rate=44100, stereo=True, buffer=128):
    """setup the pyo (sound) server
    """
    global pyoSndServer, Sound, audioDriver, duplex, maxChnls
    Sound = SoundPyo
    if not "pyo" in locals():
        import pyo  # microphone.switchOn() calls initPyo even if audioLib is something else
    # subclass the pyo.Server so that we can insert a __del__ function that shuts it down
    class _Server(pyo.Server):
        core = core  # make libs class variables so they don't get deleted first
        logging = logging

        def __del__(self):
            self.stop()
            self.core.wait(0.5)  # make sure enough time passes for the server to shutdown
            self.shutdown()
            self.core.wait(0.5)  # make sure enough time passes for the server to shutdown
            self.logging.debug("pyo sound server shutdown")  # this may never get printed

    if ".".join(map(str, pyo.getVersion())) < "0.6.4":
        Server = _Server
    else:
        Server = pyo.Server

    # if we already have a server, just re-initialize it
    if globals().has_key("pyoSndServer") and hasattr(pyoSndServer, "shutdown"):
        pyoSndServer.stop()
        core.wait(0.5)  # make sure enough time passes for the server to shutdown
        pyoSndServer.shutdown()
        core.wait(0.5)
        pyoSndServer.reinit(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        pyoSndServer.boot()
    else:
        if platform == "win32":
            # check for output device/driver
            devNames, devIDs = pyo.pa_get_output_devices()
            audioDriver, outputID = _bestDriver(devNames, devIDs)
            if outputID:
                logging.info("Using sound driver: %s (ID=%i)" % (audioDriver, outputID))
                maxOutputChnls = pyo.pa_get_output_max_channels(outputID)
            else:
                logging.warning("No audio outputs found (no speakers connected?")
                return -1
            # check for valid input (mic)
            devNames, devIDs = pyo.pa_get_input_devices()
            audioInputName, inputID = _bestDriver(devNames, devIDs)
            if inputID is not None:
                logging.info("Using sound-input driver: %s (ID=%i)" % (audioInputName, inputID))
                maxInputChnls = pyo.pa_get_input_max_channels(inputID)
                duplex = bool(maxInputChnls > 0)
            else:
                duplex = False
        else:  # for other platforms set duplex to True (if microphone is available)
            audioDriver = prefs.general["audioDriver"][0]
            maxInputChnls = pyo.pa_get_input_max_channels(pyo.pa_get_default_input())
            maxOutputChnls = pyo.pa_get_output_max_channels(pyo.pa_get_default_output())
            duplex = bool(maxInputChnls > 0)

        maxChnls = min(maxInputChnls, maxOutputChnls)
        if maxInputChnls < 1:
            logging.warning("%s.initPyo could not find microphone hardware; recording not available" % __name__)
            maxChnls = maxOutputChnls
        if maxOutputChnls < 1:
            logging.error("%s.initPyo could not find speaker hardware; sound not available" % __name__)
            return -1

        # create the instance of the server:
        if platform in ["darwin", "linux2"]:
            # for mac/linux we set the backend using the server audio param
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer, audio=audioDriver)
        else:
            # with others we just use portaudio and then set the OutputDevice below
            pyoSndServer = Server(sr=rate, nchnls=maxChnls, buffersize=buffer)

        pyoSndServer.setVerbosity(1)
        if platform == "win32":
            pyoSndServer.setOutputDevice(outputID)
            if inputID:
                pyoSndServer.setInputDevice(inputID)
        # do other config here as needed (setDuplex? setOutputDevice?)
        pyoSndServer.setDuplex(duplex)
        pyoSndServer.boot()
    core.wait(0.5)  # wait for server to boot before starting te sound stream
    pyoSndServer.start()
    try:
        Sound()  # test creation, no play
    except pyo.PyoServerStateException:
        msg = "Failed to start pyo sound Server"
        if 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()
Example #19
0
    def _setSystemInfo(self):
        # machine name
        self['systemHostName'] = platform.node()

        self['systemMemTotalRAM'], self['systemMemFreeRAM'] = getRAM()

        # locale information:
        import locale
        loc = '.'.join(map(str, locale.getlocale()))  # (None, None) -> str
        if loc == 'None.None':
            loc = locale.setlocale(locale.LC_ALL, '')
        self[
            'systemLocale'] = loc  # == the locale in use, from OS or user-pref

        # 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:
            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()

        # R (and r2py) for stats:
        try:
            Rver, err = shellCall("R --version", stderr=True)
            Rversion = Rver.splitlines()[0]
            if Rversion.startswith('R version'):
                self['systemRavailable'] = Rversion.strip()
            try:
                import rpy2
                self['systemRpy2'] = rpy2.__version__
            except:
                pass
        except:
            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:
            pass
        try:
            so, se = shellCall('gpg --version', stderr=True)
            if so.find('GnuPG') > -1:
                self['systemSec.GPGVersion'] = so.splitlines()[0]
                self['systemSec.GPGHome'] = ''.join([
                    line.replace('Home:', '').lstrip()
                    for line in so.splitlines() if line.startswith('Home:')
                ])
        except:
            pass
        try:
            import ssl
            self['systemSec.pythonSSL'] = True
        except ImportError:
            self['systemSec.pythonSSL'] = False

        # pyo for sound:
        try:
            import pyo
            self['systemPyoVersion'] = '%i.%i.%i' % pyo.getVersion()
            try:
                # requires pyo svn r1024 or higher:
                inp, out = pyo.pa_get_devices_infos()
                self['systemPyo.InputDevices'] = inp
                self['systemPyo.OutputDevices'] = out
            except AttributeError:
                pass
        except 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 take a long time to fail if there's no connection
        self['systemHaveInternetAccess'] = web.haveInternetAccess()
        if not self['systemHaveInternetAccess']:
            self['systemHaveInternetAccess'] = 'False (proxies not attempted)'
Example #20
0
print("\nSystem info:")
print(platform.platform())
if sys.platform=='darwin':
    OSXver, junk, architecture = platform.mac_ver()
    print("OS X %s running on %s" %(OSXver, architecture))

print("\nPython info")
print(sys.executable)
print(sys.version)
import numpy; print("numpy", numpy.__version__)
import scipy; print("scipy", scipy.__version__)
import matplotlib; print("matplotlib", matplotlib.__version__)
import pyglet; print("pyglet", pyglet.version)
# pyo is a new dependency, for sound:
try: 
    import pyo; print("pyo", '%i.%i.%i' % pyo.getVersion())
except:
    print('pyo [not installed]')

from psychopy import __version__
print("\nPsychoPy", __version__)

win = visual.Window([100,100])#some drivers want a window open first
print("have shaders:", win._haveShaders)
print("\nOpenGL info:")
#get info about the graphics card and drivers
print("vendor:", gl_info.get_vendor())
print("rendering engine:", gl_info.get_renderer())
print("OpenGL version:", gl_info.get_version())
print("(Selected) Extensions:")
extensionsOfInterest=['GL_ARB_multitexture',