sys.platform.startswith

Here are the examples of the python api sys.platform.startswith taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: libturpial
Source File: tools.py
View license
def detect_os():
    """ Returns a string according to the OS host """
    if sys.platform.startswith('linux'):
        return OS_LINUX
    elif sys.platform.startswith('freebsd'):
        return OS_FREEBSD
    elif sys.platform.startswith('dragonfly'):
        return OS_DFLY
    elif sys.platform.startswith('win32'):
        return OS_WINDOWS
    elif sys.platform.startswith('darwin'):
        return OS_MAC
    elif sys.platform.startswith('java'):
        return OS_JAVA
    else:
        return OS_UNKNOWN

Example 2

Project: golem
Source File: package_creator.py
View license
def get_platform():
    if sys.platform.startswith('win') or sys.platform.startswith('nt'):
        return 'win'
    elif sys.platform.startswith('linux'):
        return 'linux'
    elif sys.platform.startswith('darwin'):
        return 'osx'
    else:
        raise EnvironmentError("Unsupported platform: {}".format(sys.platform))

Example 3

Project: nginx-amplify-agent
Source File: host.py
View license
def os_name():
    if sys.platform.startswith('darwin'):
        return 'mac'
    elif sys.platform.startswith('linux'):
        return 'linux'
    elif sys.platform.startswith('freebsd'):
        return 'freebsd'
    elif sys.platform.startswith('sunos'):
        return 'solaris'
    else:
        return sys.platform

Example 4

Project: artiq
Source File: comm_tcp.py
View license
def set_keepalive(sock, after_idle, interval, max_fails):
    if sys.platform.startswith("linux"):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
    elif sys.platform.startswith("win") or sys.platform.startswith("cygwin"):
        # setting max_fails is not supported, typically ends up being 5 or 10
        # depending on Windows version
        sock.ioctl(socket.SIO_KEEPALIVE_VALS,
                   (1, after_idle*1000, interval*1000))
    else:
        logger.warning("TCP keepalive not supported on platform '%s', ignored",
                       sys.platform)

Example 5

Project: python-qinfer
Source File: config.py
View license
def preffilename():
    if sys.platform.startswith('linux') or sys.platform.startswith('darwin') or sys.platform.startswith('cygwin'):	    
        # Unix-y
        configfile = os.path.expanduser('~/.config/qinfer.conf')
    elif sys.platform.startswith('win'):
        # Windows-y
        configfile = os.path.join(os.path.expandvars('%APPDATA%'), 'qinfer.conf')
    else:
        return NotImplemented

    ensuredir(configfile)
    return configfile

Example 6

Project: reggata
Source File: cx_setup.py
View license
def get_short_sys_platform():
    if sys.platform.startswith("linux"):
        return "linux"
    elif sys.platform.startswith("win"):
        return "win"
    elif sys.platform.startswith("darwin"):
        return "mac"
    else:
        raise UnsupportedPlatform()

Example 7

Project: pyscf
Source File: misc.py
View license
def load_library(libname):
# numpy 1.6 has bug in ctypeslib.load_library, see numpy/distutils/misc_util.py
    if '1.6' in numpy.__version__:
        if (sys.platform.startswith('linux') or
            sys.platform.startswith('gnukfreebsd')):
            so_ext = '.so'
        elif sys.platform.startswith('darwin'):
            so_ext = '.dylib'
        elif sys.platform.startswith('win'):
            so_ext = '.dll'
        else:
            raise OSError('Unknown platform')
        libname_so = libname + so_ext
        return ctypes.CDLL(os.path.join(os.path.dirname(__file__), libname_so))
    else:
        _loaderpath = os.path.dirname(__file__)
        return numpy.ctypeslib.load_library(libname, _loaderpath)

Example 8

Project: xbmc-addon-watchdog
Source File: platform.py
View license
def get_platform_name():
    if sys.platform.startswith("win"):
        return PLATFORM_WINDOWS
    elif sys.platform.startswith('darwin'):
        return PLATFORM_DARWIN
    elif sys.platform.startswith('linux'):
        return PLATFORM_LINUX
    elif sys.platform.startswith('bsd'):
        return PLATFORM_BSD
    else:
        return PLATFORM_UNKNOWN

Example 9

Project: deepin-media-player
Source File: which.py
View license
def whichgen(command, path=None, verbose=0, exts=None):
    """Return a generator of full paths to the given command.
    
    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).
    """
    matches = []
    if path is None:
        usingGivenPath = 0
        path = os.environ.get("PATH", "").split(os.pathsep)
        if sys.platform.startswith("win"):
            path.insert(0, os.curdir)  # implied by Windows shell
    else:
        usingGivenPath = 1

    # Windows has the concept of a list of extensions (PATHEXT env var).
    if sys.platform.startswith("win"):
        if exts is None:
            exts = os.environ.get("PATHEXT", "").split(os.pathsep)
            # If '.exe' is not in exts then obviously this is Win9x and
            # or a bogus PATHEXT, then use a reasonable default.
            for ext in exts:
                if ext.lower() == ".exe":
                    break
            else:
                exts = ['.COM', '.EXE', '.BAT']
        elif not isinstance(exts, list):
            raise TypeError("'exts' argument must be a list or None")
    else:
        if exts is not None:
            raise WhichError("'exts' argument is not supported on "\
                             "platform '%s'" % sys.platform)
        exts = []

    # File name cannot have path separators because PATH lookup does not
    # work that way.
    if os.sep in command or os.altsep and os.altsep in command:
        pass
    else:
        for i in range(len(path)):
            dirName = path[i]
            # On windows the dirName *could* be quoted, drop the quotes
            if sys.platform.startswith("win") and len(dirName) >= 2\
               and dirName[0] == '"' and dirName[-1] == '"':
                dirName = dirName[1:-1]
            for ext in ['']+exts:
                absName = os.path.abspath(
                    os.path.normpath(os.path.join(dirName, command+ext)))
                if os.path.isfile(absName):
                    if usingGivenPath:
                        fromWhere = "from given path element %d" % i
                    elif not sys.platform.startswith("win"):
                        fromWhere = "from PATH element %d" % i
                    elif i == 0:
                        fromWhere = "from current directory"
                    else:
                        fromWhere = "from PATH element %d" % (i-1)
                    match = _cull((absName, fromWhere), matches, verbose)
                    if match:
                        if verbose:
                            yield match
                        else:
                            yield match[0]
        match = _getRegisteredExecutable(command)
        if match is not None:
            match = _cull(match, matches, verbose)
            if match:
                if verbose:
                    yield match
                else:
                    yield match[0]

Example 10

Project: cadquery-freecad-module
Source File: __init__.py
View license
def _fc_path():
    """Find FreeCAD"""
    _PATH = ""
    if _PATH:
        return _PATH

    #look for FREECAD_LIB env variable
    if os.environ.has_key('FREECAD_LIB'):
        _PATH = os.environ.get('FREECAD_LIB')
        if os.path.exists( _PATH):
            return _PATH

    if sys.platform.startswith('linux'):
        #Make some dangerous assumptions...
        for _PATH in [
                os.path.join(os.path.expanduser("~"), "lib/freecad/lib"),
                "/usr/local/lib/freecad/lib",
                "/usr/lib/freecad/lib",
                "/opt/freecad/lib/",
                "/usr/bin/freecad/lib",
                "/usr/lib/freecad",
                ]:
            if os.path.exists(_PATH):
                return _PATH

    elif sys.platform.startswith('win'):
        #try all the usual suspects
        for _PATH in [
                "c:/Program Files/FreeCAD0.12/bin",
                "c:/Program Files/FreeCAD0.13/bin",
                "c:/Program Files/FreeCAD0.14/bin",
                "c:/Program Files/FreeCAD0.15/bin",
                "c:/Program Files/FreeCAD0.16/bin",
                "c:/Program Files/FreeCAD0.17/bin",
                "c:/Program Files (x86)/FreeCAD0.12/bin",
                "c:/Program Files (x86)/FreeCAD0.13/bin",
                "c:/Program Files (x86)/FreeCAD0.14/bin",
                "c:/Program Files (x86)/FreeCAD0.15/bin",
                "c:/Program Files (x86)/FreeCAD0.16/bin",
                "c:/Program Files (x86)/FreeCAD0.17/bin",
                "c:/apps/FreeCAD0.12/bin",
                "c:/apps/FreeCAD0.13/bin",
                "c:/apps/FreeCAD0.14/bin",
                "c:/apps/FreeCAD0.15/bin",
                "c:/apps/FreeCAD0.16/bin",
                "c:/apps/FreeCAD0.17/bin",
                "c:/Program Files/FreeCAD 0.12/bin",
                "c:/Program Files/FreeCAD 0.13/bin",
                "c:/Program Files/FreeCAD 0.14/bin",
                "c:/Program Files/FreeCAD 0.15/bin",
                "c:/Program Files/FreeCAD 0.16/bin",
                "c:/Program Files/FreeCAD 0.17/bin",
                "c:/Program Files (x86)/FreeCAD 0.12/bin",
                "c:/Program Files (x86)/FreeCAD 0.13/bin",
                "c:/Program Files (x86)/FreeCAD 0.14/bin",
                "c:/Program Files (x86)/FreeCAD 0.15/bin",
                "c:/Program Files (x86)/FreeCAD 0.16/bin",
                "c:/Program Files (x86)/FreeCAD 0.17/bin",
                "c:/apps/FreeCAD 0.12/bin",
                "c:/apps/FreeCAD 0.13/bin",
                "c:/apps/FreeCAD 0.14/bin",
                "c:/apps/FreeCAD 0.15/bin",
                "c:/apps/FreeCAD 0.16/bin",
                "c:/apps/FreeCAD 0.17/bin",
                ]:
            if os.path.exists(_PATH):
                return _PATH
    elif sys.platform.startswith('darwin'):
        #Assume we're dealing with a Mac
        for _PATH in [
                "/Applications/FreeCAD.app/Contents/lib",
                os.path.join(os.path.expanduser("~"), "Library/Application Support/FreeCAD/lib"),
                ]:
            if os.path.exists(_PATH):
                return _PATH

Example 11

Project: Icarra
Source File: icarra2.py
View license
	def __init__(self, *args):
		global prefs
		self.started = False

		self.isOSX = sys.platform.startswith("darwin")
		self.isWindows = sys.platform.startswith("win")
		self.isLinux = sys.platform.startswith("linux")

		QApplication.__init__(self, *args)
		self.setApplicationName('Icarra2')
		self.setQuitOnLastWindowClosed(False)

		# Set locale one more time, QT may override it
		locale.setlocale(locale.LC_ALL, "")

		# Set global app and path
		if hasattr(sys, "frozen"):
			appPath = os.path.dirname(sys.argv[0])
		else:
			appPath = os.path.abspath(os.path.dirname(sys.argv[0]))
		appGlobal.setApp(self, appPath)
		
		# For thread safe errors
		self.errorMutex = threading.Lock()
		self.errorList = []
		
		# For checking tables
		self.checkTableMutex = threading.Lock()
		
		# For starting and ending big tasks
		self.bigTask = False
		self.bigTaskCondition = threading.Condition()
		
		# The current statusUpdate dialog, if any
		self.statusUpdate = False
		
		# Initialize members
		self.prefs = prefs
		self.stockData = StockData()
		self.ofxDebugFrame = False
		self.portfolio = False
		self.tool = False
		self.toolWidget = False
		
		# If we notified the user that we failed to connect to the icarra server
		self.notifieldFailConnected = False

		self.positiveColor = QColor(0, 153, 0)
		self.negativeColor = QColor(204, 0, 0)
		self.alternateRowColor = QColor(216, 216, 255)

		# Make sure benchmarks have been created
		checkBenchmarks(prefs)
		
		# Dictionary of portfolios used for rebuilding portfolio menu
		# So we don't have to open portfolios every time
		# Key is portfolio name, value is portfolio type ("benchmark", "bank", "brokerage", "combined")
		self.buildPortfolioMenuNames()
		
		# Nothing else if regression
		if "--regression" in args[0] or "--broker-info" in args[0] or "--rebuild" in args[0] or "--import" in args[0]:
			return

		self.plugins = PluginManager()
		
		timesRun = prefs.getTimesRun()
		splashTime = datetime.datetime.now()
		if timesRun > 0:
			# Start updater now so we can get stock data
			autoUpdater.start(self.stockData, self.prefs)

			self.splash = SplashScreenFrame()
		else:
			self.createSamplePortfolio()
			
			# Set all stocks as not having been downloaded
			# This is important incase the startup process failed
			self.stockData.db.query("update stockInfo set lastDownload='1900-01-01 00:00:00'")

			# Start after creating sample portfolio
			autoUpdater.start(self.stockData, self.prefs)

			# Load initial data, make sure we got it
			self.splash = SplashScreenFrame(firstTime = True)
			if not self.splash.running:
				autoUpdater.stop()
				self.splash.close()
				self.started = False
				message = QMessageBox(QMessageBox.Critical, "Connection error", "Unable to connect to the Icarra web server.  Please check your internet connection and try again.", flags = Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint | Qt.WindowStaysOnTopHint)
				message.exec_()
				return

		self.main = MainWindow()
		self.processEvents()

		self.main.render()
		self.processEvents()
		
		self.rebuildPortfoliosMenu()

		self.loadPortfolio(prefs.getLastPortfolio())
		self.processEvents()

		if self.prefs.getOfxDebug():
			self.startOfxDebug()

		if self.splash and timesRun == 0:
			self.splash.progress.setValue(100)

		self.checkVersion()

		self.processEvents()

		# Wait up to 2 seconds before hiding splash screen
		elapsedMs = (datetime.datetime.now() - splashTime).microseconds / 1000
		if self.splash and elapsedMs < 3000:
			self.timer = QTimer()
			interval = 3000 - elapsedMs
			self.timer.setInterval(interval)
			self.timer.setSingleShot(True)
			self.connect(self.timer, SIGNAL("timeout()"), self.hideSplash)
			self.timer.start()
		else:
			self.hideSplash()
		
		# Start timer to check for failed connected
		self.failTimer = QTimer()
		self.failTimer.setInterval(3000)
		self.connect(self.failTimer, SIGNAL("timeout()"), self.checkFailTimer)
		self.failTimer.start()

		self.prefs.incTimesRun()
		appGlobal.getApp().started = True

Example 12

Project: iot-utilities
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        with open(TESTFN, "wb") as fp:
            fp.write(b"a"*mapsize)
        with open(TESTFN, "rb") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
            self.assertEqual(m[:], b'a'*mapsize, "Readonly memory map data incorrect.")

            # Ensuring that readonly mmap can't be slice assigned
            try:
                m[:] = b'b'*mapsize
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be item assigned
            try:
                m[0] = b'b'
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write() to
            try:
                m.seek(0,0)
                m.write(b'abc')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write_byte() to
            try:
                m.seek(0,0)
                m.write_byte(b'd')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be resized
            try:
                m.resize(2*mapsize)
            except SystemError:   # resize is not universally supported
                pass
            except TypeError:
                pass
            else:
                self.fail("Able to resize readonly memory map")
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'a'*mapsize,
                                 "Readonly memory map data file was modified")

        # Opening mmap with size too big
        with open(TESTFN, "r+b") as f:
            try:
                m = mmap.mmap(f.fileno(), mapsize+1)
            except ValueError:
                # we do not expect a ValueError on Windows
                # CAUTION:  This also changes the size of the file on disk, and
                # later tests assume that the length hasn't changed.  We need to
                # repair that.
                if sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should work on Windows.")
            else:
                # we expect a ValueError on Unix, but not on Windows
                if not sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should raise ValueError.")
                m.close()
            if sys.platform.startswith('win'):
                # Repair damage from the resizing test.
                with open(TESTFN, 'r+b') as f:
                    f.truncate(mapsize)

        # Opening mmap with access=ACCESS_WRITE
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
            # Modifying write-through memory map
            m[:] = b'c'*mapsize
            self.assertEqual(m[:], b'c'*mapsize,
                   "Write-through memory map memory not updated properly.")
            m.flush()
            m.close()
        with open(TESTFN, 'rb') as f:
            stuff = f.read()
        self.assertEqual(stuff, b'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
            # Modifying copy-on-write memory map
            m[:] = b'd'*mapsize
            self.assertEqual(m[:], b'd' * mapsize,
                             "Copy-on-write memory map data not written correctly.")
            m.flush()
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'c'*mapsize,
                                 "Copy-on-write test data file should not be modified.")
            # Ensuring copy-on-write maps cannot be resized
            self.assertRaises(TypeError, m.resize, 2*mapsize)
            m.close()

        # Ensuring invalid access parameter raises exception
        with open(TESTFN, "r+b") as f:
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            with open(TESTFN, "r+b") as f:
                self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                                  flags=mmap.MAP_PRIVATE,
                                  prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 13

Project: deepin-media-player
Source File: which.py
View license
def whichgen(command, path=None, verbose=0, exts=None):
    """Return a generator of full paths to the given command.
    
    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).
    """
    matches = []
    if path is None:
        usingGivenPath = 0
        path = os.environ.get("PATH", "").split(os.pathsep)
        if sys.platform.startswith("win"):
            path.insert(0, os.curdir)  # implied by Windows shell
    else:
        usingGivenPath = 1

    # Windows has the concept of a list of extensions (PATHEXT env var).
    if sys.platform.startswith("win"):
        if exts is None:
            exts = os.environ.get("PATHEXT", "").split(os.pathsep)
            # If '.exe' is not in exts then obviously this is Win9x and
            # or a bogus PATHEXT, then use a reasonable default.
            for ext in exts:
                if ext.lower() == ".exe":
                    break
            else:
                exts = ['.COM', '.EXE', '.BAT']
        elif not isinstance(exts, list):
            raise TypeError("'exts' argument must be a list or None")
    else:
        if exts is not None:
            raise WhichError("'exts' argument is not supported on "\
                             "platform '%s'" % sys.platform)
        exts = []

    # File name cannot have path separators because PATH lookup does not
    # work that way.
    if os.sep in command or os.altsep and os.altsep in command:
        pass
    else:
        for i in range(len(path)):
            dirName = path[i]
            # On windows the dirName *could* be quoted, drop the quotes
            if sys.platform.startswith("win") and len(dirName) >= 2\
               and dirName[0] == '"' and dirName[-1] == '"':
                dirName = dirName[1:-1]
            for ext in ['']+exts:
                absName = os.path.abspath(
                    os.path.normpath(os.path.join(dirName, command+ext)))
                if os.path.isfile(absName):
                    if usingGivenPath:
                        fromWhere = "from given path element %d" % i
                    elif not sys.platform.startswith("win"):
                        fromWhere = "from PATH element %d" % i
                    elif i == 0:
                        fromWhere = "from current directory"
                    else:
                        fromWhere = "from PATH element %d" % (i-1)
                    match = _cull((absName, fromWhere), matches, verbose)
                    if match:
                        if verbose:
                            yield match
                        else:
                            yield match[0]
        match = _getRegisteredExecutable(command)
        if match is not None:
            match = _cull(match, matches, verbose)
            if match:
                if verbose:
                    yield match
                else:
                    yield match[0]

Example 14

Project: eol
Source File: which.py
View license
def whichgen(command, path=None, verbose=0, exts=None):
    """Return a generator of full paths to the given command.
    
    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).
    """
    matches = []
    if path is None:
        usingGivenPath = 0
        path = os.environ.get("PATH", "").split(os.pathsep)
        if sys.platform.startswith("win"):
            path.insert(0, os.curdir)  # implied by Windows shell
    else:
        usingGivenPath = 1

    # Windows has the concept of a list of extensions (PATHEXT env var).
    if sys.platform.startswith("win"):
        if exts is None:
            exts = os.environ.get("PATHEXT", "").split(os.pathsep)
            # If '.exe' is not in exts then obviously this is Win9x and
            # or a bogus PATHEXT, then use a reasonable default.
            for ext in exts:
                if ext.lower() == ".exe":
                    break
            else:
                exts = ['.COM', '.EXE', '.BAT']
        elif not isinstance(exts, list):
            raise TypeError("'exts' argument must be a list or None")
    else:
        if exts is not None:
            raise WhichError("'exts' argument is not supported on "\
                             "platform '%s'" % sys.platform)
        exts = []

    # File name cannot have path separators because PATH lookup does not
    # work that way.
    if os.sep in command or os.altsep and os.altsep in command:
        if os.path.exists(command):
            match = _cull((command, "explicit path given"), matches, verbose)
            if verbose:
                yield match
            else:
                yield match[0]
    else:
        for i in range(len(path)):
            dirName = path[i]
            # On windows the dirName *could* be quoted, drop the quotes
            if sys.platform.startswith("win") and len(dirName) >= 2\
               and dirName[0] == '"' and dirName[-1] == '"':
                dirName = dirName[1:-1]
            for ext in ['']+exts:
                absName = os.path.abspath(
                    os.path.normpath(os.path.join(dirName, command+ext)))
                if os.path.isfile(absName):
                    if usingGivenPath:
                        fromWhere = "from given path element %d" % i
                    elif not sys.platform.startswith("win"):
                        fromWhere = "from PATH element %d" % i
                    elif i == 0:
                        fromWhere = "from current directory"
                    else:
                        fromWhere = "from PATH element %d" % (i-1)
                    match = _cull((absName, fromWhere), matches, verbose)
                    if match:
                        if verbose:
                            yield match
                        else:
                            yield match[0]
        match = _getRegisteredExecutable(command)
        if match is not None:
            match = _cull(match, matches, verbose)
            if match:
                if verbose:
                    yield match
                else:
                    yield match[0]

Example 15

Project: idle_master_py
Source File: idle-to-ready.py
View license
def IdleBatch(appids):
	try:
		global process_idle1, process_idle2, process_idle3, process_idle4, process_idle5, process_idle6, process_idle7, process_idle8, process_idle9, process_idle10, process_idle11, process_idle12, process_idle13, process_idle14, process_idle15, process_idle16, process_idle17, process_idle18, process_idle19, process_idle20, process_idle21, process_idle22, process_idle23, process_idle24, process_idle25
		global idle_time

		idle_time = time.time()

		if sys.platform.startswith('win32'):
			start_text = "steam-idle.exe "
		elif sys.platform.startswith('darwin'):
			start_text = "./steam-idle "
		elif sys.platform.startswith('linux'):
			start_text = "./steam-idle.py "
					
		process_idle1 = subprocess.Popen(start_text + str(appids[0][0]), shell=True)
		process_idle2 = subprocess.Popen(start_text + str(appids[1][0]), shell=True)
		process_idle3 = subprocess.Popen(start_text + str(appids[2][0]), shell=True)
		process_idle4 = subprocess.Popen(start_text + str(appids[3][0]), shell=True)
		process_idle5 = subprocess.Popen(start_text + str(appids[4][0]), shell=True)
		process_idle6 = subprocess.Popen(start_text + str(appids[5][0]), shell=True)
		process_idle7 = subprocess.Popen(start_text + str(appids[6][0]), shell=True)
		process_idle8 = subprocess.Popen(start_text + str(appids[7][0]), shell=True)
		process_idle9 = subprocess.Popen(start_text + str(appids[8][0]), shell=True)
		process_idle10 = subprocess.Popen(start_text + str(appids[9][0]), shell=True)
		process_idle11 = subprocess.Popen(start_text + str(appids[10][0]), shell=True)
		process_idle12 = subprocess.Popen(start_text + str(appids[11][0]), shell=True)
		process_idle13 = subprocess.Popen(start_text + str(appids[12][0]), shell=True)
		process_idle14 = subprocess.Popen(start_text + str(appids[13][0]), shell=True)
		process_idle15 = subprocess.Popen(start_text + str(appids[14][0]), shell=True)
		process_idle16 = subprocess.Popen(start_text + str(appids[15][0]), shell=True)
		process_idle17 = subprocess.Popen(start_text + str(appids[16][0]), shell=True)
		process_idle18 = subprocess.Popen(start_text + str(appids[17][0]), shell=True)
		process_idle19 = subprocess.Popen(start_text + str(appids[18][0]), shell=True)
		process_idle20 = subprocess.Popen(start_text + str(appids[19][0]), shell=True)
		process_idle21 = subprocess.Popen(start_text + str(appids[20][0]), shell=True)
		process_idle22 = subprocess.Popen(start_text + str(appids[21][0]), shell=True)
		process_idle23 = subprocess.Popen(start_text + str(appids[22][0]), shell=True)
		process_idle24 = subprocess.Popen(start_text + str(appids[23][0]), shell=True)
		process_idle25 = subprocess.Popen(start_text + str(appids[24][0]), shell=True)
	except:
		logging.warning("All games started")

Example 16

Project: openwrt-mt7620
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        open(TESTFN, "wb").write("a"*mapsize)
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")

        # Ensuring that readonly mmap can't be slice assigned
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be item assigned
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write() to
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write_byte() to
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be resized
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            self.fail("Able to resize readonly memory map")
        f.close()
        del m, f
        self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
               "Readonly memory map data file was modified")

        # Opening mmap with size too big
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        # Opening mmap with access=ACCESS_WRITE
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        # Modifying write-through memory map
        m[:] = 'c'*mapsize
        self.assertEqual(m[:], 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        self.assertEqual(stuff, 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        # Modifying copy-on-write memory map
        m[:] = 'd'*mapsize
        self.assertEqual(m[:], 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        # Ensuring copy-on-write maps cannot be resized
        self.assertRaises(TypeError, m.resize, 2*mapsize)
        f.close()
        del m, f

        # Ensuring invalid access parameter raises exception
        f = open(TESTFN, "r+b")
        self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
        f.close()

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                              flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            f.close()

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 17

Project: TrustRouter
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        with open(TESTFN, "wb") as fp:
            fp.write(b"a"*mapsize)
        with open(TESTFN, "rb") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
            self.assertEqual(m[:], b'a'*mapsize, "Readonly memory map data incorrect.")

            # Ensuring that readonly mmap can't be slice assigned
            try:
                m[:] = b'b'*mapsize
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be item assigned
            try:
                m[0] = b'b'
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write() to
            try:
                m.seek(0,0)
                m.write(b'abc')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write_byte() to
            try:
                m.seek(0,0)
                m.write_byte(b'd')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be resized
            try:
                m.resize(2*mapsize)
            except SystemError:   # resize is not universally supported
                pass
            except TypeError:
                pass
            else:
                self.fail("Able to resize readonly memory map")
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'a'*mapsize,
                                 "Readonly memory map data file was modified")

        # Opening mmap with size too big
        with open(TESTFN, "r+b") as f:
            try:
                m = mmap.mmap(f.fileno(), mapsize+1)
            except ValueError:
                # we do not expect a ValueError on Windows
                # CAUTION:  This also changes the size of the file on disk, and
                # later tests assume that the length hasn't changed.  We need to
                # repair that.
                if sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should work on Windows.")
            else:
                # we expect a ValueError on Unix, but not on Windows
                if not sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should raise ValueError.")
                m.close()
            if sys.platform.startswith('win'):
                # Repair damage from the resizing test.
                with open(TESTFN, 'r+b') as f:
                    f.truncate(mapsize)

        # Opening mmap with access=ACCESS_WRITE
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
            # Modifying write-through memory map
            m[:] = b'c'*mapsize
            self.assertEqual(m[:], b'c'*mapsize,
                   "Write-through memory map memory not updated properly.")
            m.flush()
            m.close()
        with open(TESTFN, 'rb') as f:
            stuff = f.read()
        self.assertEqual(stuff, b'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
            # Modifying copy-on-write memory map
            m[:] = b'd'*mapsize
            self.assertEqual(m[:], b'd' * mapsize,
                             "Copy-on-write memory map data not written correctly.")
            m.flush()
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'c'*mapsize,
                                 "Copy-on-write test data file should not be modified.")
            # Ensuring copy-on-write maps cannot be resized
            self.assertRaises(TypeError, m.resize, 2*mapsize)
            m.close()

        # Ensuring invalid access parameter raises exception
        with open(TESTFN, "r+b") as f:
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            with open(TESTFN, "r+b") as f:
                self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                                  flags=mmap.MAP_PRIVATE,
                                  prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 18

Project: imagrium
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        open(TESTFN, "wb").write("a"*mapsize)
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")

        # Ensuring that readonly mmap can't be slice assigned
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be item assigned
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write() to
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write_byte() to
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be resized
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            self.fail("Able to resize readonly memory map")
        f.close()
        del m, f
        self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
               "Readonly memory map data file was modified")

        # Opening mmap with size too big
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        # Opening mmap with access=ACCESS_WRITE
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        # Modifying write-through memory map
        m[:] = 'c'*mapsize
        self.assertEqual(m[:], 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        self.assertEqual(stuff, 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        # Modifying copy-on-write memory map
        m[:] = 'd'*mapsize
        self.assertEqual(m[:], 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        # Ensuring copy-on-write maps cannot be resized
        self.assertRaises(TypeError, m.resize, 2*mapsize)
        f.close()
        del m, f

        # Ensuring invalid access parameter raises exception
        f = open(TESTFN, "r+b")
        self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
        f.close()

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                              flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            f.close()

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 19

Project: babble
Source File: test_mmap.py
View license
def test_both():
    "Test mmap module on Unix systems and Windows"

    # Create a file to be mmap'ed.
    if os.path.exists(TESTFN):
        os.unlink(TESTFN)
    f = open(TESTFN, 'w+')

    try:    # unlink TESTFN no matter what
        # Write 2 pages worth of data to the file
        f.write('\0'* PAGESIZE)
        f.write('foo')
        f.write('\0'* (PAGESIZE-3) )
        f.flush()
        m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
        f.close()

        # Simple sanity checks

        print type(m)  # SF bug 128713:  segfaulted on Linux
        print '  Position of foo:', m.find('foo') / float(PAGESIZE), 'pages'
        vereq(m.find('foo'), PAGESIZE)

        print '  Length of file:', len(m) / float(PAGESIZE), 'pages'
        vereq(len(m), 2*PAGESIZE)

        print '  Contents of byte 0:', repr(m[0])
        vereq(m[0], '\0')
        print '  Contents of first 3 bytes:', repr(m[0:3])
        vereq(m[0:3], '\0\0\0')

        # Modify the file's content
        print "\n  Modifying file's content..."
        m[0] = '3'
        m[PAGESIZE +3: PAGESIZE +3+3] = 'bar'

        # Check that the modification worked
        print '  Contents of byte 0:', repr(m[0])
        vereq(m[0], '3')
        print '  Contents of first 3 bytes:', repr(m[0:3])
        vereq(m[0:3], '3\0\0')
        print '  Contents of second page:',  repr(m[PAGESIZE-1 : PAGESIZE + 7])
        vereq(m[PAGESIZE-1 : PAGESIZE + 7], '\0foobar\0')

        m.flush()

        # Test doing a regular expression match in an mmap'ed file
        match = re.search('[A-Za-z]+', m)
        if match is None:
            print '  ERROR: regex match on mmap failed!'
        else:
            start, end = match.span(0)
            length = end - start

            print '  Regex match on mmap (page start, length of match):',
            print start / float(PAGESIZE), length

            vereq(start, PAGESIZE)
            vereq(end, PAGESIZE + 6)

        # test seeking around (try to overflow the seek implementation)
        m.seek(0,0)
        print '  Seek to zeroth byte'
        vereq(m.tell(), 0)
        m.seek(42,1)
        print '  Seek to 42nd byte'
        vereq(m.tell(), 42)
        m.seek(0,2)
        print '  Seek to last byte'
        vereq(m.tell(), len(m))

        print '  Try to seek to negative position...'
        try:
            m.seek(-1)
        except ValueError:
            pass
        else:
            verify(0, 'expected a ValueError but did not get it')

        print '  Try to seek beyond end of mmap...'
        try:
            m.seek(1,2)
        except ValueError:
            pass
        else:
            verify(0, 'expected a ValueError but did not get it')

        print '  Try to seek to negative position...'
        try:
            m.seek(-len(m)-1,2)
        except ValueError:
            pass
        else:
            verify(0, 'expected a ValueError but did not get it')

        # Try resizing map
        print '  Attempting resize()'
        try:
            m.resize(512)
        except SystemError:
            # resize() not supported
            # No messages are printed, since the output of this test suite
            # would then be different across platforms.
            pass
        else:
            # resize() is supported
            verify(len(m) == 512,
                    "len(m) is %d, but expecting 512" % (len(m),) )
            # Check that we can no longer seek beyond the new size.
            try:
                m.seek(513,0)
            except ValueError:
                pass
            else:
                verify(0, 'Could seek beyond the new size')

            # Check that the underlying file is truncated too
            # (bug #728515)
            f = open(TESTFN)
            f.seek(0, 2)
            verify(f.tell() == 512, 'Underlying file not truncated')
            f.close()
            verify(m.size() == 512, 'New size not reflected in file')

        m.close()

    finally:
        try:
            f.close()
        except OSError:
            pass
        try:
            os.unlink(TESTFN)
        except OSError:
            pass

    # Test for "access" keyword parameter
    try:
        mapsize = 10
        print "  Creating", mapsize, "byte test data file."
        open(TESTFN, "wb").write("a"*mapsize)
        print "  Opening mmap with access=ACCESS_READ"
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        verify(m[:] == 'a'*mapsize, "Readonly memory map data incorrect.")

        print "  Ensuring that readonly mmap can't be slice assigned."
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            verify(0, "Able to write to readonly memory map")

        print "  Ensuring that readonly mmap can't be item assigned."
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            verify(0, "Able to write to readonly memory map")

        print "  Ensuring that readonly mmap can't be write() to."
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            verify(0, "Able to write to readonly memory map")

        print "  Ensuring that readonly mmap can't be write_byte() to."
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            verify(0, "Able to write to readonly memory map")

        print "  Ensuring that readonly mmap can't be resized."
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            verify(0, "Able to resize readonly memory map")
        del m, f
        verify(open(TESTFN, "rb").read() == 'a'*mapsize,
               "Readonly memory map data file was modified")

        print "  Opening mmap with size too big"
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                verify(0, "Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                verify(0, "Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        print "  Opening mmap with access=ACCESS_WRITE"
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        print "  Modifying write-through memory map."
        m[:] = 'c'*mapsize
        verify(m[:] == 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        verify(stuff == 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        print "  Opening mmap with access=ACCESS_COPY"
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        print "  Modifying copy-on-write memory map."
        m[:] = 'd'*mapsize
        verify(m[:] == 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        verify(open(TESTFN, "rb").read() == 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        try:
            print "  Ensuring copy-on-write maps cannot be resized."
            m.resize(2*mapsize)
        except TypeError:
            pass
        else:
            verify(0, "Copy-on-write mmap resize did not raise exception.")
        del m, f
        try:
            print "  Ensuring invalid access parameter raises exception."
            f = open(TESTFN, "r+b")
            m = mmap.mmap(f.fileno(), mapsize, access=4)
        except ValueError:
            pass
        else:
            verify(0, "Invalid access code should have raised exception.")

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            try:
                m = mmap.mmap(f.fileno(), mapsize, flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            except ValueError:
                pass
            else:
                verify(0, "Incompatible parameters should raise ValueError.")
            f.close()
    finally:
        try:
            os.unlink(TESTFN)
        except OSError:
            pass

    print '  Try opening a bad file descriptor...'
    try:
        mmap.mmap(-2, 4096)
    except mmap.error:
        pass
    else:
        verify(0, 'expected a mmap.error but did not get it')

    # Do a tougher .find() test.  SF bug 515943 pointed out that, in 2.2,
    # searching for data with embedded \0 bytes didn't work.
    f = open(TESTFN, 'w+')

    try:    # unlink TESTFN no matter what
        data = 'aabaac\x00deef\x00\x00aa\x00'
        n = len(data)
        f.write(data)
        f.flush()
        m = mmap.mmap(f.fileno(), n)
        f.close()

        for start in range(n+1):
            for finish in range(start, n+1):
                slice = data[start : finish]
                vereq(m.find(slice), data.find(slice))
                vereq(m.find(slice + 'x'), -1)
        m.close()

    finally:
        os.unlink(TESTFN)

    # make sure a double close doesn't crash on Solaris (Bug# 665913)
    f = open(TESTFN, 'w+')

    try:    # unlink TESTFN no matter what
        f.write(2**16 * 'a') # Arbitrary character
        f.close()

        f = open(TESTFN)
        mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ)
        mf.close()
        mf.close()
        f.close()

    finally:
        os.unlink(TESTFN)

    # test mapping of entire file by passing 0 for map length
    if hasattr(os, "stat"):
        print "  Ensuring that passing 0 as map length sets map size to current file size."
        f = open(TESTFN, "w+")

        try:
            f.write(2**16 * 'm') # Arbitrary character
            f.close()

            f = open(TESTFN, "rb+")
            mf = mmap.mmap(f.fileno(), 0)
            verify(len(mf) == 2**16, "Map size should equal file size.")
            vereq(mf.read(2**16), 2**16 * "m")
            mf.close()
            f.close()

        finally:
            os.unlink(TESTFN)

    # test mapping of entire file by passing 0 for map length
    if hasattr(os, "stat"):
        print "  Ensuring that passing 0 as map length sets map size to current file size."
        f = open(TESTFN, "w+")
        try:
            f.write(2**16 * 'm') # Arbitrary character
            f.close()

            f = open(TESTFN, "rb+")
            mf = mmap.mmap(f.fileno(), 0)
            verify(len(mf) == 2**16, "Map size should equal file size.")
            vereq(mf.read(2**16), 2**16 * "m")
            mf.close()
            f.close()

        finally:
            os.unlink(TESTFN)

    # make move works everywhere (64-bit format problem earlier)
    f = open(TESTFN, 'w+')

    try:    # unlink TESTFN no matter what
        f.write("ABCDEabcde") # Arbitrary character
        f.flush()

        mf = mmap.mmap(f.fileno(), 10)
        mf.move(5, 0, 5)
        verify(mf[:] == "ABCDEABCDE", "Map move should have duplicated front 5")
        mf.close()
        f.close()

    finally:
        os.unlink(TESTFN)

    # Test that setting access to PROT_READ gives exception
    # rather than crashing
    if hasattr(mmap, "PROT_READ"):
        try:
            mapsize = 10
            open(TESTFN, "wb").write("a"*mapsize)
            f = open(TESTFN, "rb")
            m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ)
            try:
                m.write("foo")
            except TypeError:
                pass
            else:
                verify(0, "PROT_READ is not working")
        finally:
            os.unlink(TESTFN)

Example 20

Project: Icarra
Source File: icarra2.py
View license
	def __init__(self, *args):
		global prefs
		self.started = False

		self.isOSX = sys.platform.startswith("darwin")
		self.isWindows = sys.platform.startswith("win")
		self.isLinux = sys.platform.startswith("linux")

		QApplication.__init__(self, *args)
		self.setApplicationName('Icarra2')
		self.setQuitOnLastWindowClosed(False)

		# Set locale one more time, QT may override it
		locale.setlocale(locale.LC_ALL, "")

		# Set global app and path
		if hasattr(sys, "frozen"):
			appPath = os.path.dirname(sys.argv[0])
		else:
			appPath = os.path.abspath(os.path.dirname(sys.argv[0]))
		appGlobal.setApp(self, appPath)
		
		# For thread safe errors
		self.errorMutex = threading.Lock()
		self.errorList = []
		
		# For checking tables
		self.checkTableMutex = threading.Lock()
		
		# For starting and ending big tasks
		self.bigTask = False
		self.bigTaskCondition = threading.Condition()
		
		# The current statusUpdate dialog, if any
		self.statusUpdate = False
		
		# Initialize members
		self.prefs = prefs
		self.stockData = StockData()
		self.ofxDebugFrame = False
		self.portfolio = False
		self.tool = False
		self.toolWidget = False
		
		# If we notified the user that we failed to connect to the icarra server
		self.notifieldFailConnected = False

		self.positiveColor = QColor(0, 153, 0)
		self.negativeColor = QColor(204, 0, 0)
		self.alternateRowColor = QColor(216, 216, 255)

		# Make sure benchmarks have been created
		checkBenchmarks(prefs)
		
		# Dictionary of portfolios used for rebuilding portfolio menu
		# So we don't have to open portfolios every time
		# Key is portfolio name, value is portfolio type ("benchmark", "bank", "brokerage", "combined")
		self.buildPortfolioMenuNames()
		
		# Nothing else if regression
		if "--regression" in args[0] or "--broker-info" in args[0] or "--rebuild" in args[0] or "--import" in args[0]:
			return

		self.plugins = PluginManager()
		
		timesRun = prefs.getTimesRun()
		splashTime = datetime.datetime.now()
		if timesRun > 0:
			# Start updater now so we can get stock data
			autoUpdater.start(self.stockData, self.prefs)

			self.splash = SplashScreenFrame()
		else:
			self.createSamplePortfolio()
			
			# Set all stocks as not having been downloaded
			# This is important incase the startup process failed
			self.stockData.db.query("update stockInfo set lastDownload='1900-01-01 00:00:00'")

			# Start after creating sample portfolio
			autoUpdater.start(self.stockData, self.prefs)

			# Load initial data, make sure we got it
			self.splash = SplashScreenFrame(firstTime = True)
			if not self.splash.running:
				autoUpdater.stop()
				self.splash.close()
				self.started = False
				message = QMessageBox(QMessageBox.Critical, "Connection error", "Unable to connect to the Icarra web server.  Please check your internet connection and try again.", flags = Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint | Qt.WindowStaysOnTopHint)
				message.exec_()
				return

		self.main = MainWindow()
		self.processEvents()

		self.main.render()
		self.processEvents()
		
		self.rebuildPortfoliosMenu()

		self.loadPortfolio(prefs.getLastPortfolio())
		self.processEvents()

		if self.prefs.getOfxDebug():
			self.startOfxDebug()

		if self.splash and timesRun == 0:
			self.splash.progress.setValue(100)

		self.checkVersion()

		self.processEvents()

		# Wait up to 2 seconds before hiding splash screen
		elapsedMs = (datetime.datetime.now() - splashTime).microseconds / 1000
		if self.splash and elapsedMs < 3000:
			self.timer = QTimer()
			interval = 3000 - elapsedMs
			self.timer.setInterval(interval)
			self.timer.setSingleShot(True)
			self.connect(self.timer, SIGNAL("timeout()"), self.hideSplash)
			self.timer.start()
		else:
			self.hideSplash()
		
		# Start timer to check for failed connected
		self.failTimer = QTimer()
		self.failTimer.setInterval(3000)
		self.connect(self.failTimer, SIGNAL("timeout()"), self.checkFailTimer)
		self.failTimer.start()

		self.prefs.incTimesRun()
		appGlobal.getApp().started = True

Example 21

Project: holland
Source File: which.py
View license
def whichgen(command, path=None, verbose=0, exts=None):
    """Return a generator of full paths to the given command.
    
    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).
    """
    matches = []
    if path is None:
        usingGivenPath = 0
        path = os.environ.get("PATH", "").split(os.pathsep)
        if sys.platform.startswith("win"):
            path.insert(0, os.curdir)  # implied by Windows shell
    else:
        usingGivenPath = 1

    # Windows has the concept of a list of extensions (PATHEXT env var).
    if sys.platform.startswith("win"):
        if exts is None:
            exts = os.environ.get("PATHEXT", "").split(os.pathsep)
            # If '.exe' is not in exts then obviously this is Win9x and
            # or a bogus PATHEXT, then use a reasonable default.
            for ext in exts:
                if ext.lower() == ".exe":
                    break
            else:
                exts = ['.COM', '.EXE', '.BAT']
        elif not isinstance(exts, list):
            raise TypeError("'exts' argument must be a list or None")
    else:
        if exts is not None:
            raise WhichError("'exts' argument is not supported on "\
                             "platform '%s'" % sys.platform)
        exts = []

    # File name cannot have path separators because PATH lookup does not
    # work that way.
    if os.sep in command or os.altsep and os.altsep in command:
        pass
    else:
        for i in range(len(path)):
            dirName = path[i]
            # On windows the dirName *could* be quoted, drop the quotes
            if sys.platform.startswith("win") and len(dirName) >= 2\
               and dirName[0] == '"' and dirName[-1] == '"':
                dirName = dirName[1:-1]
            for ext in ['']+exts:
                absName = os.path.abspath(
                    os.path.normpath(os.path.join(dirName, command+ext)))
                if os.path.isfile(absName):
                    if usingGivenPath:
                        fromWhere = "from given path element %d" % i
                    elif not sys.platform.startswith("win"):
                        fromWhere = "from PATH element %d" % i
                    elif i == 0:
                        fromWhere = "from current directory"
                    else:
                        fromWhere = "from PATH element %d" % (i-1)
                    match = _cull((absName, fromWhere), matches, verbose)
                    if match:
                        if verbose:
                            yield match
                        else:
                            yield match[0]
        match = _getRegisteredExecutable(command)
        if match is not None:
            match = _cull(match, matches, verbose)
            if match:
                if verbose:
                    yield match
                else:
                    yield match[0]

Example 22

Project: jhbuild
Source File: environment.py
View license
def setup_env(prefix):
    '''set environment variables for using prefix'''

    os.environ['JHBUILD_PREFIX'] = prefix
    addpath('JHBUILD_PREFIXES', prefix)

    # LD_LIBRARY_PATH
    libdir = os.path.join(prefix, 'lib')
    addpath('LD_LIBRARY_PATH', libdir)
    os.environ['JHBUILD_LIBDIR'] = libdir

    # LDFLAGS and C_INCLUDE_PATH are required for autoconf configure
    # scripts to find modules that do not use pkg-config (such as guile
    # looking for gmp, or wireless-tools for NetworkManager)
    # (see bug #377724 and bug #545018)

    # This path doesn't always get passed to addpath so we fix it here
    if sys.platform.startswith('win'):
        libdir = subprocess_win32.fix_path_for_msys(libdir)
    os.environ['LDFLAGS'] = ('-L%s ' % libdir) + os.environ.get('LDFLAGS', '')

    includedir = os.path.join(prefix, 'include')
    addpath('C_INCLUDE_PATH', includedir)
    addpath('OBJC_INCLUDE_PATH', includedir)
    addpath('CPLUS_INCLUDE_PATH', includedir)

    # On Mac OS X, we use DYLD_FALLBACK_LIBRARY_PATH
    if sys.platform == 'darwin':
        addpath('DYLD_FALLBACK_LIBRARY_PATH', libdir)

    # PATH
    bindir = os.path.join(prefix, 'bin')
    addpath('PATH', bindir)

    # MANPATH
    manpathdir = os.path.join(prefix, 'share', 'man')
    addpath('MANPATH', '')
    addpath('MANPATH', manpathdir)
    # Setting MANPATH on *BSD causes man to ignore its default search path,
    # so we need to add the default search path to MANPATH.
    if sys.platform.startswith('freebsd') or sys.platform.startswith('dragonfly'):
        systemmanpath = get_output('manpath -q', extra_env={'MANPATH': ''})
        systemmanpath = systemmanpath.strip().split(':')
    elif sys.platform.startswith('netbsd'):
        # Running 'man -p' without specifying a manual page name causes it to
        # exit with status 1.
        systemmanpath = get_output('man -p || true', extra_env={'MANPATH': ''})
        systemmanpath = map(os.path.dirname, systemmanpath.strip().split('\n'))
    elif sys.platform.startswith('openbsd'):
        # I cannot find a command that prints the default search path on
        # OpenBSD, so I add paths found in the default /etc/man.conf here.
        systemmanpath = [ '/usr/share/man', '/usr/X11R6/man', '/usr/local/man' ]
    else:
        systemmanpath = []
    for systemmanpathdir in systemmanpath:
        addpath('MANPATH', systemmanpathdir, prepend=False)

    # INFOPATH
    infopathdir = os.path.join(prefix, 'share', 'info')
    addpath('INFOPATH', infopathdir)

    # PKG_CONFIG_PATH
    pkgconfigdatadir = os.path.join(prefix, 'share', 'pkgconfig')
    pkgconfigdir = os.path.join(libdir, 'pkgconfig')
    addpath('PKG_CONFIG_PATH', pkgconfigdatadir)
    addpath('PKG_CONFIG_PATH', pkgconfigdir)

    # GI_TYPELIB_PATH
    typelibpath = os.path.join(libdir, 'girepository-1.0')
    addpath('GI_TYPELIB_PATH', typelibpath)

    # XDG_DATA_DIRS
    xdgdatadir = os.path.join(prefix, 'share')
    addpath('XDG_DATA_DIRS', xdgdatadir)

    # XDG_CONFIG_DIRS
    xdgconfigdir = os.path.join(prefix, 'etc', 'xdg')
    addpath('XDG_CONFIG_DIRS', xdgconfigdir)

    # XCURSOR_PATH
    xcursordir = os.path.join(prefix, 'share', 'icons')
    addpath('XCURSOR_PATH', xcursordir)

    # GST_PLUGIN_PATH
    gstplugindir = os.path.join(libdir , 'gstreamer-0.10')
    if os.path.exists(gstplugindir):
        addpath('GST_PLUGIN_PATH', gstplugindir)

    # GST_PLUGIN_PATH_1_0
    gstplugindir = os.path.join(libdir , 'gstreamer-1.0')
    if os.path.exists(gstplugindir):
        addpath('GST_PLUGIN_PATH_1_0', gstplugindir)

    # GST_REGISTRY
    gstregistry = os.path.join(prefix, '_jhbuild', 'gstreamer-0.10.registry')
    os.environ['GST_REGISTRY'] = gstregistry

    # GST_REGISTRY_1_0
    gstregistry = os.path.join(prefix, '_jhbuild', 'gstreamer-1.0.registry')
    os.environ['GST_REGISTRY_1_0'] = gstregistry

    # ACLOCAL_PATH
    aclocalpath = os.path.join(prefix, 'share', 'aclocal')
    addpath('ACLOCAL_PATH', aclocalpath)

    # PERL5LIB
    perl5lib = os.path.join(prefix, 'lib', 'perl5')
    addpath('PERL5LIB', perl5lib)

    # These two variables are so that people who use "jhbuild shell"
    # can tweak their shell prompts and such to show "I'm under jhbuild".
    # The first variable is the obvious one to look for; the second
    # one is for historical reasons.
    os.environ['UNDER_JHBUILD'] = 'true'
    os.environ['CERTIFIED_GNOMIE'] = 'yes'

    # PYTHONPATH
    # We use a sitecustomize script to make sure we get the correct path
    # with the various versions of python that the user may run.
    if PKGDATADIR:
        addpath('PYTHONPATH', os.path.join(PKGDATADIR, 'sitecustomize'))
    else:
        addpath('PYTHONPATH', os.path.join(SRCDIR, 'jhbuild', 'sitecustomize'))

Example 23

Project: pymo
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        open(TESTFN, "wb").write("a"*mapsize)
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")

        # Ensuring that readonly mmap can't be slice assigned
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be item assigned
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write() to
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write_byte() to
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be resized
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            self.fail("Able to resize readonly memory map")
        f.close()
        del m, f
        self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
               "Readonly memory map data file was modified")

        # Opening mmap with size too big
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        # Opening mmap with access=ACCESS_WRITE
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        # Modifying write-through memory map
        m[:] = 'c'*mapsize
        self.assertEqual(m[:], 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        self.assertEqual(stuff, 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        # Modifying copy-on-write memory map
        m[:] = 'd'*mapsize
        self.assertEqual(m[:], 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        # Ensuring copy-on-write maps cannot be resized
        self.assertRaises(TypeError, m.resize, 2*mapsize)
        f.close()
        del m, f

        # Ensuring invalid access parameter raises exception
        f = open(TESTFN, "r+b")
        self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
        f.close()

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                              flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            f.close()

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 24

Project: cadquery
Source File: __init__.py
View license
def _fc_path():
    """Find FreeCAD"""
    _PATH = ""
    if _PATH:
        return _PATH

    #look for FREECAD_LIB env variable
    if os.environ.has_key('FREECAD_LIB'):
        _PATH = os.environ.get('FREECAD_LIB')
        if os.path.exists( _PATH):
            return _PATH

    if sys.platform.startswith('linux'):
        #Make some dangerous assumptions...
        for _PATH in [
                os.path.join(os.path.expanduser("~"), "lib/freecad/lib"),
                "/usr/local/lib/freecad/lib",
                "/usr/lib/freecad/lib",
                "/opt/freecad/lib/",
                "/usr/bin/freecad/lib",
                "/usr/lib/freecad",
                ]:
            if os.path.exists(_PATH):
                return _PATH

    elif sys.platform.startswith('win'):
        #try all the usual suspects
        for _PATH in [
                "c:/Program Files/FreeCAD0.12/bin",
                "c:/Program Files/FreeCAD0.13/bin",
                "c:/Program Files/FreeCAD0.14/bin",
                "c:/Program Files/FreeCAD0.15/bin",
                "c:/Program Files/FreeCAD0.16/bin",
                "c:/Program Files/FreeCAD0.17/bin",
                "c:/Program Files (x86)/FreeCAD0.12/bin",
                "c:/Program Files (x86)/FreeCAD0.13/bin",
                "c:/Program Files (x86)/FreeCAD0.14/bin",
                "c:/Program Files (x86)/FreeCAD0.15/bin",
                "c:/Program Files (x86)/FreeCAD0.16/bin",
                "c:/Program Files (x86)/FreeCAD0.17/bin",
                "c:/apps/FreeCAD0.12/bin",
                "c:/apps/FreeCAD0.13/bin",
                "c:/apps/FreeCAD0.14/bin",
                "c:/apps/FreeCAD0.15/bin",
                "c:/apps/FreeCAD0.16/bin",
                "c:/apps/FreeCAD0.17/bin",
                "c:/Program Files/FreeCAD 0.12/bin",
                "c:/Program Files/FreeCAD 0.13/bin",
                "c:/Program Files/FreeCAD 0.14/bin",
                "c:/Program Files/FreeCAD 0.15/bin",
                "c:/Program Files/FreeCAD 0.16/bin",
                "c:/Program Files/FreeCAD 0.17/bin",
                "c:/Program Files (x86)/FreeCAD 0.12/bin",
                "c:/Program Files (x86)/FreeCAD 0.13/bin",
                "c:/Program Files (x86)/FreeCAD 0.14/bin",
                "c:/Program Files (x86)/FreeCAD 0.15/bin",
                "c:/Program Files (x86)/FreeCAD 0.16/bin",
                "c:/Program Files (x86)/FreeCAD 0.17/bin",
                "c:/apps/FreeCAD 0.12/bin",
                "c:/apps/FreeCAD 0.13/bin",
                "c:/apps/FreeCAD 0.14/bin",
                "c:/apps/FreeCAD 0.15/bin",
                "c:/apps/FreeCAD 0.16/bin",
                "c:/apps/FreeCAD 0.17/bin",
                ]:
            if os.path.exists(_PATH):
                return _PATH
    elif sys.platform.startswith('darwin'):
        #Assume we're dealing with a Mac
        for _PATH in [
                "/Applications/FreeCAD.app/Contents/lib",
                os.path.join(os.path.expanduser("~"), "Library/Application Support/FreeCAD/lib"),
                ]:
            if os.path.exists(_PATH):
                return _PATH

Example 25

Project: datafari
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        open(TESTFN, "wb").write("a"*mapsize)
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")

        # Ensuring that readonly mmap can't be slice assigned
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be item assigned
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write() to
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write_byte() to
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be resized
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            self.fail("Able to resize readonly memory map")
        f.close()
        del m, f
        self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
               "Readonly memory map data file was modified")

        # Opening mmap with size too big
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        # Opening mmap with access=ACCESS_WRITE
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        # Modifying write-through memory map
        m[:] = 'c'*mapsize
        self.assertEqual(m[:], 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        self.assertEqual(stuff, 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        # Modifying copy-on-write memory map
        m[:] = 'd'*mapsize
        self.assertEqual(m[:], 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        # Ensuring copy-on-write maps cannot be resized
        self.assertRaises(TypeError, m.resize, 2*mapsize)
        f.close()
        del m, f

        # Ensuring invalid access parameter raises exception
        f = open(TESTFN, "r+b")
        self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
        f.close()

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                              flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            f.close()

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 26

Project: chipsec
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        open(TESTFN, "wb").write("a"*mapsize)
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")

        # Ensuring that readonly mmap can't be slice assigned
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be item assigned
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write() to
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write_byte() to
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be resized
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            self.fail("Able to resize readonly memory map")
        f.close()
        del m, f
        self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
               "Readonly memory map data file was modified")

        # Opening mmap with size too big
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        # Opening mmap with access=ACCESS_WRITE
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        # Modifying write-through memory map
        m[:] = 'c'*mapsize
        self.assertEqual(m[:], 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        self.assertEqual(stuff, 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        # Modifying copy-on-write memory map
        m[:] = 'd'*mapsize
        self.assertEqual(m[:], 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        # Ensuring copy-on-write maps cannot be resized
        self.assertRaises(TypeError, m.resize, 2*mapsize)
        f.close()
        del m, f

        # Ensuring invalid access parameter raises exception
        f = open(TESTFN, "r+b")
        self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
        f.close()

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                              flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            f.close()

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 27

Project: vlc-python
Source File: header.py
View license
def find_lib():
    dll = None
    plugin_path = None
    if sys.platform.startswith('linux'):
        p = find_library('vlc')
        try:
            dll = ctypes.CDLL(p)
        except OSError:  # may fail
            dll = ctypes.CDLL('libvlc.so.5')
    elif sys.platform.startswith('win'):
        p = find_library('libvlc.dll')
        if p is None:
            try:  # some registry settings
                import _winreg as w  # leaner than win32api, win32con
                for r in w.HKEY_LOCAL_MACHINE, w.HKEY_CURRENT_USER:
                    try:
                        r = w.OpenKey(r, 'Software\\VideoLAN\\VLC')
                        plugin_path, _ = w.QueryValueEx(r, 'InstallDir')
                        w.CloseKey(r)
                        break
                    except w.error:
                        pass
            except ImportError:  # no PyWin32
                pass
            if plugin_path is None:
                 # try some standard locations.
                for p in ('Program Files\\VideoLan\\', 'VideoLan\\',
                          'Program Files\\',           ''):
                    p = 'C:\\' + p + 'VLC\\libvlc.dll'
                    if os.path.exists(p):
                        plugin_path = os.path.dirname(p)
                        break
            if plugin_path is not None:  # try loading
                p = os.getcwd()
                os.chdir(plugin_path)
                 # if chdir failed, this will raise an exception
                dll = ctypes.CDLL('libvlc.dll')
                 # restore cwd after dll has been loaded
                os.chdir(p)
            else:  # may fail
                dll = ctypes.CDLL('libvlc.dll')
        else:
            plugin_path = os.path.dirname(p)
            dll = ctypes.CDLL(p)

    elif sys.platform.startswith('darwin'):
        # FIXME: should find a means to configure path
        d = '/Applications/VLC.app/Contents/MacOS/'
        p = d + 'lib/libvlc.dylib'
        if os.path.exists(p):
            dll = ctypes.CDLL(p)
            d += 'modules'
            if os.path.isdir(d):
                plugin_path = d
        else:  # hope, some PATH is set...
            dll = ctypes.CDLL('libvlc.dylib')

    else:
        raise NotImplementedError('%s: %s not supported' % (sys.argv[0], sys.platform))

    return (dll, plugin_path)

Example 28

Project: brython
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        with open(TESTFN, "wb") as fp:
            fp.write(b"a"*mapsize)
        with open(TESTFN, "rb") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
            self.assertEqual(m[:], b'a'*mapsize, "Readonly memory map data incorrect.")

            # Ensuring that readonly mmap can't be slice assigned
            try:
                m[:] = b'b'*mapsize
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be item assigned
            try:
                m[0] = b'b'
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write() to
            try:
                m.seek(0,0)
                m.write(b'abc')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write_byte() to
            try:
                m.seek(0,0)
                m.write_byte(b'd')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be resized
            try:
                m.resize(2*mapsize)
            except SystemError:   # resize is not universally supported
                pass
            except TypeError:
                pass
            else:
                self.fail("Able to resize readonly memory map")
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'a'*mapsize,
                                 "Readonly memory map data file was modified")

        # Opening mmap with size too big
        with open(TESTFN, "r+b") as f:
            try:
                m = mmap.mmap(f.fileno(), mapsize+1)
            except ValueError:
                # we do not expect a ValueError on Windows
                # CAUTION:  This also changes the size of the file on disk, and
                # later tests assume that the length hasn't changed.  We need to
                # repair that.
                if sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should work on Windows.")
            else:
                # we expect a ValueError on Unix, but not on Windows
                if not sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should raise ValueError.")
                m.close()
            if sys.platform.startswith('win'):
                # Repair damage from the resizing test.
                with open(TESTFN, 'r+b') as f:
                    f.truncate(mapsize)

        # Opening mmap with access=ACCESS_WRITE
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
            # Modifying write-through memory map
            m[:] = b'c'*mapsize
            self.assertEqual(m[:], b'c'*mapsize,
                   "Write-through memory map memory not updated properly.")
            m.flush()
            m.close()
        with open(TESTFN, 'rb') as f:
            stuff = f.read()
        self.assertEqual(stuff, b'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
            # Modifying copy-on-write memory map
            m[:] = b'd'*mapsize
            self.assertEqual(m[:], b'd' * mapsize,
                             "Copy-on-write memory map data not written correctly.")
            m.flush()
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'c'*mapsize,
                                 "Copy-on-write test data file should not be modified.")
            # Ensuring copy-on-write maps cannot be resized
            self.assertRaises(TypeError, m.resize, 2*mapsize)
            m.close()

        # Ensuring invalid access parameter raises exception
        with open(TESTFN, "r+b") as f:
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            with open(TESTFN, "r+b") as f:
                self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                                  flags=mmap.MAP_PRIVATE,
                                  prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 29

Project: iot-utilities
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        with open(TESTFN, "wb") as fp:
            fp.write(b"a"*mapsize)
        with open(TESTFN, "rb") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
            self.assertEqual(m[:], b'a'*mapsize, "Readonly memory map data incorrect.")

            # Ensuring that readonly mmap can't be slice assigned
            try:
                m[:] = b'b'*mapsize
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be item assigned
            try:
                m[0] = b'b'
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write() to
            try:
                m.seek(0,0)
                m.write(b'abc')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write_byte() to
            try:
                m.seek(0,0)
                m.write_byte(b'd')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be resized
            try:
                m.resize(2*mapsize)
            except SystemError:   # resize is not universally supported
                pass
            except TypeError:
                pass
            else:
                self.fail("Able to resize readonly memory map")
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'a'*mapsize,
                                 "Readonly memory map data file was modified")

        # Opening mmap with size too big
        with open(TESTFN, "r+b") as f:
            try:
                m = mmap.mmap(f.fileno(), mapsize+1)
            except ValueError:
                # we do not expect a ValueError on Windows
                # CAUTION:  This also changes the size of the file on disk, and
                # later tests assume that the length hasn't changed.  We need to
                # repair that.
                if sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should work on Windows.")
            else:
                # we expect a ValueError on Unix, but not on Windows
                if not sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should raise ValueError.")
                m.close()
            if sys.platform.startswith('win'):
                # Repair damage from the resizing test.
                with open(TESTFN, 'r+b') as f:
                    f.truncate(mapsize)

        # Opening mmap with access=ACCESS_WRITE
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
            # Modifying write-through memory map
            m[:] = b'c'*mapsize
            self.assertEqual(m[:], b'c'*mapsize,
                   "Write-through memory map memory not updated properly.")
            m.flush()
            m.close()
        with open(TESTFN, 'rb') as f:
            stuff = f.read()
        self.assertEqual(stuff, b'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
            # Modifying copy-on-write memory map
            m[:] = b'd'*mapsize
            self.assertEqual(m[:], b'd' * mapsize,
                             "Copy-on-write memory map data not written correctly.")
            m.flush()
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'c'*mapsize,
                                 "Copy-on-write test data file should not be modified.")
            # Ensuring copy-on-write maps cannot be resized
            self.assertRaises(TypeError, m.resize, 2*mapsize)
            m.close()

        # Ensuring invalid access parameter raises exception
        with open(TESTFN, "r+b") as f:
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            with open(TESTFN, "r+b") as f:
                self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                                  flags=mmap.MAP_PRIVATE,
                                  prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 30

Project: iot-utilities
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        with open(TESTFN, "wb") as fp:
            fp.write(b"a"*mapsize)
        with open(TESTFN, "rb") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
            self.assertEqual(m[:], b'a'*mapsize, "Readonly memory map data incorrect.")

            # Ensuring that readonly mmap can't be slice assigned
            try:
                m[:] = b'b'*mapsize
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be item assigned
            try:
                m[0] = b'b'
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write() to
            try:
                m.seek(0,0)
                m.write(b'abc')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write_byte() to
            try:
                m.seek(0,0)
                m.write_byte(b'd')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be resized
            try:
                m.resize(2*mapsize)
            except SystemError:   # resize is not universally supported
                pass
            except TypeError:
                pass
            else:
                self.fail("Able to resize readonly memory map")
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'a'*mapsize,
                                 "Readonly memory map data file was modified")

        # Opening mmap with size too big
        with open(TESTFN, "r+b") as f:
            try:
                m = mmap.mmap(f.fileno(), mapsize+1)
            except ValueError:
                # we do not expect a ValueError on Windows
                # CAUTION:  This also changes the size of the file on disk, and
                # later tests assume that the length hasn't changed.  We need to
                # repair that.
                if sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should work on Windows.")
            else:
                # we expect a ValueError on Unix, but not on Windows
                if not sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should raise ValueError.")
                m.close()
            if sys.platform.startswith('win'):
                # Repair damage from the resizing test.
                with open(TESTFN, 'r+b') as f:
                    f.truncate(mapsize)

        # Opening mmap with access=ACCESS_WRITE
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
            # Modifying write-through memory map
            m[:] = b'c'*mapsize
            self.assertEqual(m[:], b'c'*mapsize,
                   "Write-through memory map memory not updated properly.")
            m.flush()
            m.close()
        with open(TESTFN, 'rb') as f:
            stuff = f.read()
        self.assertEqual(stuff, b'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
            # Modifying copy-on-write memory map
            m[:] = b'd'*mapsize
            self.assertEqual(m[:], b'd' * mapsize,
                             "Copy-on-write memory map data not written correctly.")
            m.flush()
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'c'*mapsize,
                                 "Copy-on-write test data file should not be modified.")
            # Ensuring copy-on-write maps cannot be resized
            self.assertRaises(TypeError, m.resize, 2*mapsize)
            m.close()

        # Ensuring invalid access parameter raises exception
        with open(TESTFN, "r+b") as f:
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            with open(TESTFN, "r+b") as f:
                self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                                  flags=mmap.MAP_PRIVATE,
                                  prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 31

Project: iot-utilities
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        with open(TESTFN, "wb") as fp:
            fp.write(b"a"*mapsize)
        with open(TESTFN, "rb") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
            self.assertEqual(m[:], b'a'*mapsize, "Readonly memory map data incorrect.")

            # Ensuring that readonly mmap can't be slice assigned
            try:
                m[:] = b'b'*mapsize
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be item assigned
            try:
                m[0] = b'b'
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write() to
            try:
                m.seek(0,0)
                m.write(b'abc')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be write_byte() to
            try:
                m.seek(0,0)
                m.write_byte(b'd')
            except TypeError:
                pass
            else:
                self.fail("Able to write to readonly memory map")

            # Ensuring that readonly mmap can't be resized
            try:
                m.resize(2*mapsize)
            except SystemError:   # resize is not universally supported
                pass
            except TypeError:
                pass
            else:
                self.fail("Able to resize readonly memory map")
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'a'*mapsize,
                                 "Readonly memory map data file was modified")

        # Opening mmap with size too big
        with open(TESTFN, "r+b") as f:
            try:
                m = mmap.mmap(f.fileno(), mapsize+1)
            except ValueError:
                # we do not expect a ValueError on Windows
                # CAUTION:  This also changes the size of the file on disk, and
                # later tests assume that the length hasn't changed.  We need to
                # repair that.
                if sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should work on Windows.")
            else:
                # we expect a ValueError on Unix, but not on Windows
                if not sys.platform.startswith('win'):
                    self.fail("Opening mmap with size+1 should raise ValueError.")
                m.close()
            if sys.platform.startswith('win'):
                # Repair damage from the resizing test.
                with open(TESTFN, 'r+b') as f:
                    f.truncate(mapsize)

        # Opening mmap with access=ACCESS_WRITE
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
            # Modifying write-through memory map
            m[:] = b'c'*mapsize
            self.assertEqual(m[:], b'c'*mapsize,
                   "Write-through memory map memory not updated properly.")
            m.flush()
            m.close()
        with open(TESTFN, 'rb') as f:
            stuff = f.read()
        self.assertEqual(stuff, b'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        with open(TESTFN, "r+b") as f:
            m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
            # Modifying copy-on-write memory map
            m[:] = b'd'*mapsize
            self.assertEqual(m[:], b'd' * mapsize,
                             "Copy-on-write memory map data not written correctly.")
            m.flush()
            with open(TESTFN, "rb") as fp:
                self.assertEqual(fp.read(), b'c'*mapsize,
                                 "Copy-on-write test data file should not be modified.")
            # Ensuring copy-on-write maps cannot be resized
            self.assertRaises(TypeError, m.resize, 2*mapsize)
            m.close()

        # Ensuring invalid access parameter raises exception
        with open(TESTFN, "r+b") as f:
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            with open(TESTFN, "r+b") as f:
                self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                                  flags=mmap.MAP_PRIVATE,
                                  prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 32

Project: cmdln
Source File: which.py
View license
def whichgen(command, path=None, verbose=0, exts=None):
    """Return a generator of full paths to the given command.
    
    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).
    """
    matches = []
    if path is None:
        usingGivenPath = 0
        path = os.environ.get("PATH", "").split(os.pathsep)
        if sys.platform.startswith("win"):
            path.insert(0, os.curdir)  # implied by Windows shell
    else:
        usingGivenPath = 1

    # Windows has the concept of a list of extensions (PATHEXT env var).
    if sys.platform.startswith("win"):
        if exts is None:
            exts = os.environ.get("PATHEXT", "").split(os.pathsep)
            # If '.exe' is not in exts then obviously this is Win9x and
            # or a bogus PATHEXT, then use a reasonable default.
            for ext in exts:
                if ext.lower() == ".exe":
                    break
            else:
                exts = ['.COM', '.EXE', '.BAT']
        elif not isinstance(exts, list):
            raise TypeError("'exts' argument must be a list or None")
    else:
        if exts is not None:
            raise WhichError("'exts' argument is not supported on "\
                             "platform '%s'" % sys.platform)
        exts = []

    # File name cannot have path separators because PATH lookup does not
    # work that way.
    if os.sep in command or os.altsep and os.altsep in command:
        pass
    else:
        for i in range(len(path)):
            dirName = path[i]
            # On windows the dirName *could* be quoted, drop the quotes
            if sys.platform.startswith("win") and len(dirName) >= 2\
               and dirName[0] == '"' and dirName[-1] == '"':
                dirName = dirName[1:-1]
            for ext in ['']+exts:
                absName = os.path.abspath(
                    os.path.normpath(os.path.join(dirName, command+ext)))
                if os.path.isfile(absName):
                    if usingGivenPath:
                        fromWhere = "from given path element %d" % i
                    elif not sys.platform.startswith("win"):
                        fromWhere = "from PATH element %d" % i
                    elif i == 0:
                        fromWhere = "from current directory"
                    else:
                        fromWhere = "from PATH element %d" % (i-1)
                    match = _cull((absName, fromWhere), matches, verbose)
                    if match:
                        if verbose:
                            yield match
                        else:
                            yield match[0]
        match = _getRegisteredExecutable(command)
        if match is not None:
            match = _cull(match, matches, verbose)
            if match:
                if verbose:
                    yield match
                else:
                    yield match[0]

Example 33

Project: idle_master_py
Source File: idle-to-ready.py
View license
def IdleBatch(appids):
	try:
		global process_idle1, process_idle2, process_idle3, process_idle4, process_idle5, process_idle6, process_idle7, process_idle8, process_idle9, process_idle10, process_idle11, process_idle12, process_idle13, process_idle14, process_idle15, process_idle16, process_idle17, process_idle18, process_idle19, process_idle20, process_idle21, process_idle22, process_idle23, process_idle24, process_idle25
		global idle_time

		idle_time = time.time()

		if sys.platform.startswith('win32'):
			start_text = "steam-idle.exe "
		elif sys.platform.startswith('darwin'):
			start_text = "./steam-idle "
		elif sys.platform.startswith('linux'):
			start_text = "./steam-idle.py "
					
		process_idle1 = subprocess.Popen(start_text + str(appids[0][0]), shell=True)
		process_idle2 = subprocess.Popen(start_text + str(appids[1][0]), shell=True)
		process_idle3 = subprocess.Popen(start_text + str(appids[2][0]), shell=True)
		process_idle4 = subprocess.Popen(start_text + str(appids[3][0]), shell=True)
		process_idle5 = subprocess.Popen(start_text + str(appids[4][0]), shell=True)
		process_idle6 = subprocess.Popen(start_text + str(appids[5][0]), shell=True)
		process_idle7 = subprocess.Popen(start_text + str(appids[6][0]), shell=True)
		process_idle8 = subprocess.Popen(start_text + str(appids[7][0]), shell=True)
		process_idle9 = subprocess.Popen(start_text + str(appids[8][0]), shell=True)
		process_idle10 = subprocess.Popen(start_text + str(appids[9][0]), shell=True)
		process_idle11 = subprocess.Popen(start_text + str(appids[10][0]), shell=True)
		process_idle12 = subprocess.Popen(start_text + str(appids[11][0]), shell=True)
		process_idle13 = subprocess.Popen(start_text + str(appids[12][0]), shell=True)
		process_idle14 = subprocess.Popen(start_text + str(appids[13][0]), shell=True)
		process_idle15 = subprocess.Popen(start_text + str(appids[14][0]), shell=True)
		process_idle16 = subprocess.Popen(start_text + str(appids[15][0]), shell=True)
		process_idle17 = subprocess.Popen(start_text + str(appids[16][0]), shell=True)
		process_idle18 = subprocess.Popen(start_text + str(appids[17][0]), shell=True)
		process_idle19 = subprocess.Popen(start_text + str(appids[18][0]), shell=True)
		process_idle20 = subprocess.Popen(start_text + str(appids[19][0]), shell=True)
		process_idle21 = subprocess.Popen(start_text + str(appids[20][0]), shell=True)
		process_idle22 = subprocess.Popen(start_text + str(appids[21][0]), shell=True)
		process_idle23 = subprocess.Popen(start_text + str(appids[22][0]), shell=True)
		process_idle24 = subprocess.Popen(start_text + str(appids[23][0]), shell=True)
		process_idle25 = subprocess.Popen(start_text + str(appids[24][0]), shell=True)
	except:
		logging.warning("All games started")

Example 34

Project: cadquery-freecad-module
Source File: __init__.py
View license
def _fc_path():
    """Find FreeCAD"""
    _PATH = ""
    if _PATH:
        return _PATH

    #look for FREECAD_LIB env variable
    if os.environ.has_key('FREECAD_LIB'):
        _PATH = os.environ.get('FREECAD_LIB')
        if os.path.exists( _PATH):
            return _PATH

    if sys.platform.startswith('linux'):
        #Make some dangerous assumptions...
        for _PATH in [
                os.path.join(os.path.expanduser("~"), "lib/freecad/lib"),
                "/usr/local/lib/freecad/lib",
                "/usr/lib/freecad/lib",
                "/opt/freecad/lib/",
                "/usr/bin/freecad/lib",
                "/usr/lib/freecad",
                ]:
            if os.path.exists(_PATH):
                return _PATH

    elif sys.platform.startswith('win'):
        #try all the usual suspects
        for _PATH in [
                "c:/Program Files/FreeCAD0.12/bin",
                "c:/Program Files/FreeCAD0.13/bin",
                "c:/Program Files/FreeCAD0.14/bin",
                "c:/Program Files/FreeCAD0.15/bin",
                "c:/Program Files/FreeCAD0.16/bin",
                "c:/Program Files/FreeCAD0.17/bin",
                "c:/Program Files (x86)/FreeCAD0.12/bin",
                "c:/Program Files (x86)/FreeCAD0.13/bin",
                "c:/Program Files (x86)/FreeCAD0.14/bin",
                "c:/Program Files (x86)/FreeCAD0.15/bin",
                "c:/Program Files (x86)/FreeCAD0.16/bin",
                "c:/Program Files (x86)/FreeCAD0.17/bin",
                "c:/apps/FreeCAD0.12/bin",
                "c:/apps/FreeCAD0.13/bin",
                "c:/apps/FreeCAD0.14/bin",
                "c:/apps/FreeCAD0.15/bin",
                "c:/apps/FreeCAD0.16/bin",
                "c:/apps/FreeCAD0.17/bin",
                "c:/Program Files/FreeCAD 0.12/bin",
                "c:/Program Files/FreeCAD 0.13/bin",
                "c:/Program Files/FreeCAD 0.14/bin",
                "c:/Program Files/FreeCAD 0.15/bin",
                "c:/Program Files/FreeCAD 0.16/bin",
                "c:/Program Files/FreeCAD 0.17/bin",
                "c:/Program Files (x86)/FreeCAD 0.12/bin",
                "c:/Program Files (x86)/FreeCAD 0.13/bin",
                "c:/Program Files (x86)/FreeCAD 0.14/bin",
                "c:/Program Files (x86)/FreeCAD 0.15/bin",
                "c:/Program Files (x86)/FreeCAD 0.16/bin",
                "c:/Program Files (x86)/FreeCAD 0.17/bin",
                "c:/apps/FreeCAD 0.12/bin",
                "c:/apps/FreeCAD 0.13/bin",
                "c:/apps/FreeCAD 0.14/bin",
                "c:/apps/FreeCAD 0.15/bin",
                "c:/apps/FreeCAD 0.16/bin",
                "c:/apps/FreeCAD 0.17/bin",
                ]:
            if os.path.exists(_PATH):
                return _PATH
    elif sys.platform.startswith('darwin'):
        #Assume we're dealing with a Mac
        for _PATH in [
                "/Applications/FreeCAD.app/Contents/lib",
                os.path.join(os.path.expanduser("~"), "Library/Application Support/FreeCAD/lib"),
                ]:
            if os.path.exists(_PATH):
                return _PATH

Example 35

Project: python-matlab-bridge
Source File: make.py
View license
def which_matlab():
    try:
        matlab_path = which('matlab').strip()
        matlab_path = make_str(matlab_path)
        return os.path.dirname(os.path.realpath(matlab_path))
    except (OSError, subprocess.CalledProcessError):
        def ensure_path(path, extension=''):
            return os.path.isdir(path) and \
                os.path.isfile(os.path.join(path, "matlab" + extension))

        # need to guess the location of MATLAB
        if sys.platform.startswith("darwin"):
            MATLABs = [os.path.join("/Applications", i, "bin")
                       for i in os.listdir("/Applications")
                       if i.startswith("MATLAB_R")]
            # only want ones with MATLAB executables
            # sort so we can get the latest
            MATLABs = list(sorted(filter(ensure_path, MATLABs)))
            return MATLABs[-1] if len(MATLABs) > 0 else None
        elif sys.platform.startswith("win32"):
            MATLAB_loc = "C:\\Program Files\\MATLAB"
            print(MATLAB_loc)
            if not os.path.isdir(MATLAB_loc):
                return None
            MATLABs = [os.path.join(MATLAB_loc, i, "bin")
                       for i in os.listdir(MATLAB_loc)]
            print(MATLABs)
            print(i)
            # only want ones with MATLAB executables
            # sort so we can get the latest
            MATLABs = list(sorted(filter(lambda x: ensure_path(x, ".exe"),
                                         MATLABs)))
            print(MATLABs)
            return MATLABs[-1] if len(MATLABs) > 0 else None
        elif sys.platform.startswith("linux"):
            MATLAB_loc = "/usr/local/MATLAB/"
            if not os.path.isdir(MATLAB_loc):
                return None
            MATLABs = [os.path.join(MATLAB_loc, i, "bin")
                       for i in os.listdir(MATLAB_loc)
                       if i.startswith("R")]
            # only want ones with MATLAB executables
            # sort so we can get the latest
            MATLABs = list(sorted(filter(ensure_path, MATLABs)))
            return MATLABs[-1] if len(MATLABs) > 0 else None

Example 36

Project: rituals
Source File: which.py
View license
def whichgen(command, path=None, verbose=0, exts=None): # pylint: disable=too-many-branches, too-many-statements
    """Return a generator of full paths to the given command.

    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).
    """
    matches = []
    if path is None:
        using_given_path = 0
        path = os.environ.get("PATH", "").split(os.pathsep)
        if sys.platform.startswith("win"):
            path.insert(0, os.curdir)  # implied by Windows shell
    else:
        using_given_path = 1

    # Windows has the concept of a list of extensions (PATHEXT env var).
    if sys.platform.startswith("win"):
        if exts is None:
            exts = os.environ.get("PATHEXT", "").split(os.pathsep)
            # If '.exe' is not in exts then obviously this is Win9x and
            # or a bogus PATHEXT, then use a reasonable default.
            for ext in exts:
                if ext.lower() == ".exe":
                    break
            else:
                exts = ['.COM', '.EXE', '.BAT']
        elif not isinstance(exts, list):
            raise TypeError("'exts' argument must be a list or None")
    else:
        if exts is not None:
            raise WhichError("'exts' argument is not supported on platform '%s'" % sys.platform)
        exts = []

    # File name cannot have path separators because PATH lookup does not
    # work that way.
    if os.sep in command or os.altsep and os.altsep in command:
        pass
    else:
        for i in range(len(path)):
            dir_name = path[i]
            # On windows the dir_name *could* be quoted, drop the quotes
            if sys.platform.startswith("win") and len(dir_name) >= 2 and dir_name[0] == '"' and dir_name[-1] == '"':
                dir_name = dir_name[1:-1]
            for ext in ['']+exts:
                abs_name = os.path.abspath(os.path.normpath(os.path.join(dir_name, command+ext)))
                if os.path.isfile(abs_name):
                    if using_given_path:
                        from_where = "from given path element %d" % i
                    elif not sys.platform.startswith("win"):
                        from_where = "from PATH element %d" % i
                    elif i == 0:
                        from_where = "from current directory"
                    else:
                        from_where = "from PATH element %d" % (i-1)
                    match = _cull((abs_name, from_where), matches, verbose)
                    if match:
                        if verbose:
                            yield match
                        else:
                            yield match[0]
        match = _get_registered_executable(command)
        if match is not None:
            match = _cull(match, matches, verbose)
            if match:
                if verbose:
                    yield match
                else:
                    yield match[0]

Example 37

Project: openwrt-mt7620
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        open(TESTFN, "wb").write("a"*mapsize)
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")

        # Ensuring that readonly mmap can't be slice assigned
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be item assigned
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write() to
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write_byte() to
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be resized
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            self.fail("Able to resize readonly memory map")
        f.close()
        del m, f
        self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
               "Readonly memory map data file was modified")

        # Opening mmap with size too big
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        # Opening mmap with access=ACCESS_WRITE
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        # Modifying write-through memory map
        m[:] = 'c'*mapsize
        self.assertEqual(m[:], 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        self.assertEqual(stuff, 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        # Modifying copy-on-write memory map
        m[:] = 'd'*mapsize
        self.assertEqual(m[:], 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        # Ensuring copy-on-write maps cannot be resized
        self.assertRaises(TypeError, m.resize, 2*mapsize)
        f.close()
        del m, f

        # Ensuring invalid access parameter raises exception
        f = open(TESTFN, "r+b")
        self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
        f.close()

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                              flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            f.close()

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 38

Project: rituals
Source File: which.py
View license
def whichgen(command, path=None, verbose=0, exts=None): # pylint: disable=too-many-branches, too-many-statements
    """Return a generator of full paths to the given command.

    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).
    """
    matches = []
    if path is None:
        using_given_path = 0
        path = os.environ.get("PATH", "").split(os.pathsep)
        if sys.platform.startswith("win"):
            path.insert(0, os.curdir)  # implied by Windows shell
    else:
        using_given_path = 1

    # Windows has the concept of a list of extensions (PATHEXT env var).
    if sys.platform.startswith("win"):
        if exts is None:
            exts = os.environ.get("PATHEXT", "").split(os.pathsep)
            # If '.exe' is not in exts then obviously this is Win9x and
            # or a bogus PATHEXT, then use a reasonable default.
            for ext in exts:
                if ext.lower() == ".exe":
                    break
            else:
                exts = ['.COM', '.EXE', '.BAT']
        elif not isinstance(exts, list):
            raise TypeError("'exts' argument must be a list or None")
    else:
        if exts is not None:
            raise WhichError("'exts' argument is not supported on platform '%s'" % sys.platform)
        exts = []

    # File name cannot have path separators because PATH lookup does not
    # work that way.
    if os.sep in command or os.altsep and os.altsep in command:
        pass
    else:
        for i in range(len(path)):
            dir_name = path[i]
            # On windows the dir_name *could* be quoted, drop the quotes
            if sys.platform.startswith("win") and len(dir_name) >= 2 and dir_name[0] == '"' and dir_name[-1] == '"':
                dir_name = dir_name[1:-1]
            for ext in ['']+exts:
                abs_name = os.path.abspath(os.path.normpath(os.path.join(dir_name, command+ext)))
                if os.path.isfile(abs_name):
                    if using_given_path:
                        from_where = "from given path element %d" % i
                    elif not sys.platform.startswith("win"):
                        from_where = "from PATH element %d" % i
                    elif i == 0:
                        from_where = "from current directory"
                    else:
                        from_where = "from PATH element %d" % (i-1)
                    match = _cull((abs_name, from_where), matches, verbose)
                    if match:
                        if verbose:
                            yield match
                        else:
                            yield match[0]
        match = _get_registered_executable(command)
        if match is not None:
            match = _cull(match, matches, verbose)
            if match:
                if verbose:
                    yield match
                else:
                    yield match[0]

Example 39

Project: gns3-gui
Source File: main.py
View license
def main():
    """
    Entry point for GNS3 GUI.
    """

    # Sometimes (for example at first launch) the OSX app service launcher add
    # an extra argument starting with -psn_. We filter it
    if sys.platform.startswith("darwin"):
        sys.argv = [a for a in sys.argv if not a.startswith("-psn_")]

    parser = argparse.ArgumentParser()
    parser.add_argument("project", help="load a GNS3 project (.gns3)", metavar="path", nargs="?")
    parser.add_argument("--version", help="show the version", action="version", version=__version__)
    parser.add_argument("--debug", help="print out debug messages", action="store_true", default=False)
    parser.add_argument("--config", help="Configuration file")
    options = parser.parse_args()
    exception_file_path = "exceptions.log"

    if options.config:
        LocalConfig.instance(config_file=options.config)
    else:
        LocalConfig.instance()

    if options.project:
        options.project = os.path.abspath(options.project)

    if hasattr(sys, "frozen"):
        # We add to the path where the OS search executable our binary location starting by GNS3
        # packaged binary
        frozen_dir = os.path.dirname(os.path.abspath(sys.executable))
        if sys.platform.startswith("darwin"):
            frozen_dirs = [
                frozen_dir,
                os.path.normpath(os.path.join(frozen_dir, '..', 'Resources'))
            ]
        elif sys.platform.startswith("win"):
            frozen_dirs = [
                frozen_dir,
                os.path.normpath(os.path.join(frozen_dir, 'dynamips')),
                os.path.normpath(os.path.join(frozen_dir, 'vpcs'))
            ]

        os.environ["PATH"] = os.pathsep.join(frozen_dirs) + os.pathsep + os.environ.get("PATH", "")

        if options.project:
            os.chdir(frozen_dir)

    def exceptionHook(exception, value, tb):

        if exception == KeyboardInterrupt:
            sys.exit(0)

        lines = traceback.format_exception(exception, value, tb)
        print("****** Exception detected, traceback information saved in {} ******".format(exception_file_path))
        print("\nPLEASE REPORT ON https://www.gns3.com\n")
        print("".join(lines))
        try:
            curdate = time.strftime("%d %b %Y %H:%M:%S")
            logfile = open(exception_file_path, "a", encoding="utf-8")
            logfile.write("=== GNS3 {} traceback on {} ===\n".format(__version__, curdate))
            logfile.write("".join(lines))
            logfile.close()
        except OSError as e:
            print("Could not save traceback to {}: {}".format(os.path.normpath(exception_file_path), e))

        if not sys.stdout.isatty():
            # if stdout is not a tty (redirected to the console view),
            # then print the exception on stderr too.
            print("".join(lines), file=sys.stderr)

        if exception is MemoryError:
            print("YOUR SYSTEM IS OUT OF MEMORY!")
        else:
            CrashReport.instance().captureException(exception, value, tb)

    # catch exceptions to write them in a file
    sys.excepthook = exceptionHook

    current_year = datetime.date.today().year
    print("GNS3 GUI version {}".format(__version__))
    print("Copyright (c) 2007-{} GNS3 Technologies Inc.".format(current_year))

    # we only support Python 3 version >= 3.4
    if sys.version_info < (3, 4):
        raise SystemExit("Python 3.4 or higher is required")

    if parse_version(QtCore.QT_VERSION_STR) < parse_version("5.0.0"):
        raise SystemExit("Requirement is PyQt5 version 5.0.0 or higher, got version {}".format(QtCore.QT_VERSION_STR))

    if parse_version(psutil.__version__) < parse_version("2.2.1"):
        raise SystemExit("Requirement is psutil version 2.2.1 or higher, got version {}".format(psutil.__version__))

    # check for the correct locale
    # (UNIX/Linux only)
    locale_check()

    try:
        os.getcwd()
    except FileNotFoundError:
        log.critical("the current working directory doesn't exist")
        return

    # always use the INI format on Windows and OSX (because we don't like the registry and plist files)
    if sys.platform.startswith('win') or sys.platform.startswith('darwin'):
        QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)

    if sys.platform.startswith('win') and hasattr(sys, "frozen"):
        try:
            import win32console
            import win32con
            import win32gui
        except ImportError:
            raise SystemExit("Python for Windows extensions must be installed.")

        if not options.debug:
            try:
                # hide the console
                console_window = win32console.GetConsoleWindow()
                win32gui.ShowWindow(console_window, win32con.SW_HIDE)
            except win32console.error as e:
                print("warning: could not allocate console: {}".format(e))

    global app
    app = Application(sys.argv)

    # save client logging info to a file
    logfile = os.path.join(LocalConfig.configDirectory(), "gns3_gui.log")

    # on debug enable logging to stdout
    if options.debug:
        root_logger = init_logger(logging.DEBUG, logfile)
    else:
        root_logger = init_logger(logging.INFO, logfile)

    # update the exception file path to have it in the same directory as the settings file.
    exception_file_path = os.path.join(LocalConfig.configDirectory(), exception_file_path)

    global mainwindow
    mainwindow = MainWindow()

    # On OSX we can receive the file to open from a system event
    # loadPath is smart and will load only if a path is present
    mainwindow.ready_signal.connect(lambda: mainwindow.loadPath(app.open_file_at_startup))
    mainwindow.ready_signal.connect(lambda: mainwindow.loadPath(options.project))
    app.file_open_signal.connect(lambda path: mainwindow.loadPath(path))

    # Manage Ctrl + C or kill command
    def sigint_handler(*args):
        log.info("Signal received exiting the application")
        mainwindow.setSoftExit(False)
        app.closeAllWindows()
    orig_sigint = signal.signal(signal.SIGINT, sigint_handler)
    orig_sigterm = signal.signal(signal.SIGTERM, sigint_handler)

    mainwindow.show()

    exit_code = app.exec_()

    signal.signal(signal.SIGINT, orig_sigint)
    signal.signal(signal.SIGTERM, orig_sigterm)

    delattr(MainWindow, "_instance")

    # We force deleting the app object otherwise it's segfault on Fedora
    del app
    # We force a full garbage collect before exit
    # for unknow reason otherwise Qt Segfault on OSX in some
    # conditions
    import gc
    gc.collect()

    sys.exit(exit_code)

Example 40

Project: gns3-server
Source File: vmware_vm.py
View license
    @asyncio.coroutine
    def _add_ubridge_connection(self, nio, adapter_number):
        """
        Creates a connection in uBridge.

        :param nio: NIO instance
        :param adapter_number: adapter number
        """

        block_host_traffic = self.manager.config.get_section_config("VMware").getboolean("block_host_traffic", False)
        vnet = "ethernet{}.vnet".format(adapter_number)
        if vnet not in self._vmx_pairs:
            raise VMwareError("vnet {} not in VMX file".format(vnet))
        yield from self._ubridge_hypervisor.send("bridge create {name}".format(name=vnet))
        vmnet_interface = os.path.basename(self._vmx_pairs[vnet])
        if sys.platform.startswith("linux"):
            yield from self._ubridge_hypervisor.send('bridge add_nio_linux_raw {name} "{interface}"'.format(name=vnet,
                                                                                                            interface=vmnet_interface))
        elif sys.platform.startswith("win"):
            windows_interfaces = interfaces()
            npf = None
            source_mac = None
            for interface in windows_interfaces:
                if "netcard" in interface and vmnet_interface in interface["netcard"]:
                    npf = interface["id"]
                    source_mac = interface["mac_address"]
                elif vmnet_interface in interface["name"]:
                    npf = interface["id"]
                    source_mac = interface["mac_address"]
            if npf:
                yield from self._ubridge_hypervisor.send('bridge add_nio_ethernet {name} "{interface}"'.format(name=vnet,
                                                                                                               interface=npf))
            else:
                raise VMwareError("Could not find NPF id for VMnet interface {}".format(vmnet_interface))

            if block_host_traffic:
                if source_mac:
                    yield from self._ubridge_hypervisor.send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=vnet,
                                                                                                                          mac=source_mac))
                else:
                    log.warn("Could not block host network traffic on {} (no MAC address found)".format(vmnet_interface))

        elif sys.platform.startswith("darwin"):
            yield from self._ubridge_hypervisor.send('bridge add_nio_fusion_vmnet {name} "{interface}"'.format(name=vnet,
                                                                                                               interface=vmnet_interface))
        else:
            yield from self._ubridge_hypervisor.send('bridge add_nio_ethernet {name} "{interface}"'.format(name=vnet,
                                                                                                           interface=vmnet_interface))

        if isinstance(nio, NIOUDP):
            yield from self._ubridge_hypervisor.send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=vnet,
                                                                                                                lport=nio.lport,
                                                                                                                rhost=nio.rhost,
                                                                                                                rport=nio.rport))
        elif isinstance(nio, NIOTAP):
            yield from self._ubridge_hypervisor.send('bridge add_nio_tap {name} {tap}'.format(name=vnet, tap=nio.tap_device))

        if nio.capturing:
            yield from self._ubridge_hypervisor.send('bridge start_capture {name} "{pcap_file}"'.format(name=vnet,
                                                                                                        pcap_file=nio.pcap_output_file))

        yield from self._ubridge_hypervisor.send('bridge start {name}'.format(name=vnet))

Example 41

Project: python-matlab-bridge
Source File: make.py
View license
def which_matlab():
    try:
        matlab_path = which('matlab').strip()
        matlab_path = make_str(matlab_path)
        return os.path.dirname(os.path.realpath(matlab_path))
    except (OSError, subprocess.CalledProcessError):
        def ensure_path(path, extension=''):
            return os.path.isdir(path) and \
                os.path.isfile(os.path.join(path, "matlab" + extension))

        # need to guess the location of MATLAB
        if sys.platform.startswith("darwin"):
            MATLABs = [os.path.join("/Applications", i, "bin")
                       for i in os.listdir("/Applications")
                       if i.startswith("MATLAB_R")]
            # only want ones with MATLAB executables
            # sort so we can get the latest
            MATLABs = list(sorted(filter(ensure_path, MATLABs)))
            return MATLABs[-1] if len(MATLABs) > 0 else None
        elif sys.platform.startswith("win32"):
            MATLAB_loc = "C:\\Program Files\\MATLAB"
            print(MATLAB_loc)
            if not os.path.isdir(MATLAB_loc):
                return None
            MATLABs = [os.path.join(MATLAB_loc, i, "bin")
                       for i in os.listdir(MATLAB_loc)]
            print(MATLABs)
            print(i)
            # only want ones with MATLAB executables
            # sort so we can get the latest
            MATLABs = list(sorted(filter(lambda x: ensure_path(x, ".exe"),
                                         MATLABs)))
            print(MATLABs)
            return MATLABs[-1] if len(MATLABs) > 0 else None
        elif sys.platform.startswith("linux"):
            MATLAB_loc = "/usr/local/MATLAB/"
            if not os.path.isdir(MATLAB_loc):
                return None
            MATLABs = [os.path.join(MATLAB_loc, i, "bin")
                       for i in os.listdir(MATLAB_loc)
                       if i.startswith("R")]
            # only want ones with MATLAB executables
            # sort so we can get the latest
            MATLABs = list(sorted(filter(ensure_path, MATLABs)))
            return MATLABs[-1] if len(MATLABs) > 0 else None

Example 42

Project: pyzmq
Source File: setup.py
View license
    def bundle_libzmq_extension(self):
        bundledir = "bundled"
        ext_modules = self.distribution.ext_modules
        if ext_modules and any(m.name == 'zmq.libzmq' for m in ext_modules):
            # I've already been run
            return
        
        line()
        info("Using bundled libzmq")
        
        # fetch sources for libzmq extension:
        if not os.path.exists(bundledir):
            os.makedirs(bundledir)
        
        fetch_libzmq(bundledir)
        
        stage_platform_hpp(pjoin(bundledir, 'zeromq'))

        sources = [pjoin('buildutils', 'initlibzmq.c')]
        sources += glob(pjoin(bundledir, 'zeromq', 'src', '*.cpp'))

        includes = [
            pjoin(bundledir, 'zeromq', 'include')
        ]

        if bundled_version < (4, 2, 0):
            tweetnacl = pjoin(bundledir, 'zeromq', 'tweetnacl')
            tweetnacl_sources = glob(pjoin(tweetnacl, 'src', '*.c'))

            randombytes = pjoin(tweetnacl, 'contrib', 'randombytes')
            if sys.platform.startswith('win'):
                tweetnacl_sources.append(pjoin(randombytes, 'winrandom.c'))
            else:
                tweetnacl_sources.append(pjoin(randombytes, 'devurandom.c'))

            sources += tweetnacl_sources
            includes.append(pjoin(tweetnacl, 'src'))
            includes.append(randombytes)
        else:
            # >= 4.2
            sources += glob(pjoin(bundledir, 'zeromq', 'src', 'tweetnacl.c'))

        # construct the Extensions:
        libzmq = Extension(
            'zmq.libzmq',
            sources=sources,
            include_dirs=includes,
        )
        
        # register the extension:
        self.distribution.ext_modules.insert(0, libzmq)
        
        # use tweetnacl to provide CURVE support
        libzmq.define_macros.append(('ZMQ_HAVE_CURVE', 1))
        libzmq.define_macros.append(('ZMQ_USE_TWEETNACL', 1))
        
        # select polling subsystem based on platform
        if sys.platform  == 'darwin' or 'bsd' in sys.platform:
            libzmq.define_macros.append(('ZMQ_USE_KQUEUE', 1))
        elif 'linux' in sys.platform:
            libzmq.define_macros.append(('ZMQ_USE_EPOLL', 1))
        elif sys.platform.startswith('win'):
            libzmq.define_macros.append(('ZMQ_USE_SELECT', 1))
        else:
            # this may not be sufficiently precise
            libzmq.define_macros.append(('ZMQ_USE_POLL', 1))
        
        if sys.platform.startswith('win'):
            # include defines from zeromq msvc project:
            libzmq.define_macros.append(('FD_SETSIZE', 16384))
            libzmq.define_macros.append(('DLL_EXPORT', 1))
            libzmq.define_macros.append(('_CRT_SECURE_NO_WARNINGS', 1))
            
            # When compiling the C++ code inside of libzmq itself, we want to
            # avoid "warning C4530: C++ exception handler used, but unwind
            # semantics are not enabled. Specify /EHsc".
            if self.compiler_type == 'msvc':
                libzmq.extra_compile_args.append('/EHsc')
            elif self.compiler_type == 'mingw32':
                libzmq.define_macros.append(('ZMQ_HAVE_MINGW32', 1))

            # And things like sockets come from libraries that must be named.
            libzmq.libraries.extend(['rpcrt4', 'ws2_32', 'advapi32'])
            
            # bundle MSCVP redist
            if self.config['bundle_msvcp']:
                cc = new_compiler(compiler=self.compiler_type)
                cc.initialize()
                # get vc_redist location via private API
                try:
                    cc._vcruntime_redist
                except AttributeError:
                    # fatal error if env set, warn otherwise
                    msg = fatal if os.environ.get("PYZMQ_BUNDLE_CRT") else warn
                    msg("Failed to get cc._vcruntime via private API, not bundling CRT")
                if cc._vcruntime_redist:
                    redist_dir, dll = os.path.split(cc._vcruntime_redist)
                    to_bundle = [
                        pjoin(redist_dir, dll.replace('vcruntime', name))
                        for name in ('msvcp', 'concrt')
                    ]
                    for src in to_bundle:
                        dest = localpath('zmq', basename(src))
                        info("Copying %s -> %s" % (src, dest))
                        # copyfile to avoid permission issues
                        shutil.copyfile(src, dest)

        else:
            libzmq.include_dirs.append(bundledir)

            # check if we need to link against Realtime Extensions library
            cc = new_compiler(compiler=self.compiler_type)
            cc.output_dir = self.build_temp
            if not sys.platform.startswith(('darwin', 'freebsd')):
                line()
                info("checking for timer_create")
                if not cc.has_function('timer_create'):
                    info("no timer_create, linking librt")
                    libzmq.libraries.append('rt')
                else:
                    info("ok")
                
                if pypy:
                    # seem to need explicit libstdc++ on linux + pypy
                    # not sure why
                    libzmq.libraries.append("stdc++")
        
        # copy the header files to the source tree.
        bundledincludedir = pjoin('zmq', 'include')
        if not os.path.exists(bundledincludedir):
            os.makedirs(bundledincludedir)
        if not os.path.exists(pjoin(self.build_lib, bundledincludedir)):
            os.makedirs(pjoin(self.build_lib, bundledincludedir))
        
        for header in glob(pjoin(bundledir, 'zeromq', 'include', '*.h')):
            shutil.copyfile(header, pjoin(bundledincludedir, basename(header)))
            shutil.copyfile(header, pjoin(self.build_lib, bundledincludedir, basename(header)))
        
        # update other extensions, with bundled settings
        self.config['libzmq_extension'] = True
        self.init_settings_from_config()
        self.save_config('config', self.config)

Example 43

Project: exaproxy
Source File: daemon.py
View license
	def __init__ (self,configuration):
		self.filemax = 0
		self.daemonize = configuration.daemon.daemonize
		self.user = configuration.daemon.user
		self.log = Logger('daemon', configuration.log.daemon)
		#mask = os.umask(0137)

		if configuration.web.debug:
			self.log.critical('WARNING: python remote execution via the web server is enabled')

		if configuration.daemon.reactor == 'epoll' and not sys.platform.startswith('linux'):
			self.log.error('exaproxy.daemon.reactor can only be epoll only on Linux')
			sys.exit(1)

		if configuration.daemon.reactor == 'kqueue' and not sys.platform.startswith('freebsd') and not sys.platform.startswith('darwin'):
			self.log.error('exaproxy.daemon.reactor can only be kqueue only on FreeBSD or OS X')
			sys.exit(1)

		self.nb_descriptors = 40  # some to be safe ...
		self.nb_descriptors += configuration.http.connections*2    # one socket for client and server connection
		self.nb_descriptors += configuration.web.connections       # one socket per web client connection
		self.nb_descriptors += configuration.redirector.maximum*2  # one socket per pipe to the thread and one for the forked process
		self.nb_descriptors += configuration.dns.retries*10        # some sockets for the DNS

		if configuration.daemon.reactor == 'select':
			if self.nb_descriptors > 1024:
				self.log.critical('the select reactor is not very scalable, and can only handle 1024 simultaneous descriptors')
				self.log.critical('your configuration requires %d file descriptors' % self.nb_descriptors)
				self.log.critical('please increase your system maximum limit, alternatively you can reduce')
				self.log.critical('exaproxy.http.connections, exaproxy.web.connections and/or configuration.redirector.maximum')
				self.log.critical('shutting down, we can not safely run with these settings')
				sys.exit(1)

		soft,hard = resource.getrlimit(resource.RLIMIT_NOFILE)

		if soft < self.nb_descriptors:
			try:
				self.log.warning('not enough file descriptor available, increasing the limit from %d to %d' % (soft,self.nb_descriptors))
				soft_limit,hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
				wanted_limit = min(self.nb_descriptors, hard_limit if hard_limit > 0 else self.nb_descriptors)
				# default on mac are (256,-1)
				resource.setrlimit(resource.RLIMIT_NOFILE, (wanted_limit, hard_limit))

			except (resource.error,ValueError),e:
				self.log.warning('problem when trying to increase resource limit : %s' % str(e))

		soft,hard = resource.getrlimit(resource.RLIMIT_NOFILE)
		if soft < self.nb_descriptors:
			self.log.critical('could not increase file descriptor limit to %d, limit is still %d' % (self.nb_descriptors,signed(soft)))
			self.log.critical('on Linux you may want to increase the value in /proc/sys/fs/file-max')
			self.log.critical('please increase your system maximum limit, alternatively you can reduce')
			self.log.critical('exaproxy.http.connections, exaproxy.web.connections and/or configuration.redirector.maximum')
			return

		# on linux :
		# need to get page size, and box memory, read /proc/sys/net/ipv4/tcp_mem and make sure the values are same.
		# look at /proc/sys/net/ipv4/tcp_max_orphans and make sure the value is high enough for the number of FD
		# > free -m
		# > getconf PAGESIZE
		# we should monitor and graph some of the values of /proc/net/sockstat and add it to our web page
		# like TCP inuse, orphan, etc.


		self.log.info('for information, your configuration requires %d available file descriptors' % self.nb_descriptors)
		self.filemax = self.nb_descriptors

Example 44

Project: expyriment
Source File: _get_system_info.py
View license
def get_system_info(as_string=False):
    """Print system information to standard out and return as a dictionary.

    Parameters
    ----------
    as_string : boolean, optional
        Print as string instead of dict (default = False)

    """

    info = {}

    # Get platform specific info for Linux
    if sys.platform.startswith("linux"):
        os_platform = "Linux"
        os_name = platform.linux_distribution()[0]
        details = []
        if os.environ.has_key("XDG_CURRENT_DESKTOP"):
            details.append(os.environ["XDG_CURRENT_DESKTOP"])
        if os.environ.has_key("DESKTOP_SESSION"):
            details.append(os.environ["DESKTOP_SESSION"])
        if details != []:
            os_details = ", ".join(details)
        else:
            os_details = ""
        os_version = platform.linux_distribution()[1]

        try:
            hardware_cpu_details = ""
            with open('/proc/cpuinfo') as f:
                for line in f:
                    if line.startswith("model name"):
                        hardware_cpu_details = line.split(":")[1].strip()
        except:
            hardware_cpu_details = ""

        try:
            with open('/proc/meminfo') as f:
                for line in f:
                    if line.startswith("MemTotal"):
                        mem_total = \
                            int(line.split(":")[1].strip()[:-2].strip()) / 1024
                    if line.startswith("MemFree"):
                        mem_free = \
                            int(line.split(":")[1].strip()[:-2].strip()) / 1024
                    if line.startswith("Buffers"):
                        mem_buffers = \
                            int(line.split(":")[1].strip()[:-2].strip()) / 1024
                    if line.startswith("Cached"):
                        mem_cached = \
                            int(line.split(":")[1].strip()[:-2].strip()) / 1024
            hardware_memory_total = str(mem_total) + " MB"
            hardware_memory_free = str(mem_free + mem_buffers + mem_cached) + \
                                   " MB"

        except:
            hardware_memory_total = ""
            hardware_memory_free = ""

        try:
            hardware_audio_card = ""
            cards = []
            p = subprocess.Popen(['lspci'], stdout=subprocess.PIPE)
            for line in p.stdout:
                if "Audio" in line:
                    cards.append(line.split(":")[-1].strip())
            p.wait()
            hardware_audio_card = ", ".join(cards)
        except:
            try:
                hardware_audio_card = ""
                cards = []
                with open('/proc/asound/cards') as f:
                    for line in f:
                        if line.startswith(" 0"):
                            cards.append(line.split(":")[1].strip())
                hardware_audio_card = ", ".join(cards)
            except:
                hardware_audio_card = ""

        try:
            current_folder = os.path.split(os.path.realpath(sys.argv[0]))[0]
            s = os.statvfs(current_folder)
            disk_total = int((s.f_frsize * s.f_blocks) / 1024 ** 2)
            disk_free = int((s.f_frsize * s.f_bavail) / 1024 ** 2)
            hardware_disk_space_total = str(disk_total) + " MB"
            hardware_disk_space_free = str(disk_free) + " MB"
        except:
            hardware_disk_space_total = ""
            hardware_disk_space_free = ""

        try:
            hardware_video_card = ""
            cards = []
            p = subprocess.Popen(['lspci'], stdout=subprocess.PIPE)
            for line in p.stdout:
                if "VGA" in line:
                    cards.append(line.split(":")[-1].strip())
            p.wait()
            hardware_video_card = ", ".join(cards)
        except:
            hardware_video_card = ""

    # Get platform specific info for Windows
    elif sys.platform.startswith("win"):
        os_platform = "Windows"
        os_name = "Windows"
        os_details = platform.win32_ver()[2]
        os_version = platform.win32_ver()[1]

        try:
            hardware_cpu_details = str(_get_registry_value(
                "HKEY_LOCAL_MACHINE",
                "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
                "ProcessorNameString"))
        except:
            hardware_cpu_details = ""

        try:
            import ctypes
            class MEMORYSTATUSEX(ctypes.Structure):
                _fields_ = [("dwLength", ctypes.c_uint),
                            ("dwMemoryLoad", ctypes.c_uint),
                            ("ullTotalPhys", ctypes.c_ulonglong),
                            ("ullAvailPhys", ctypes.c_ulonglong),
                            ("ullTotalPageFile", ctypes.c_ulonglong),
                            ("ullAvailPageFile", ctypes.c_ulonglong),
                            ("ullTotalVirtual", ctypes.c_ulonglong),
                            ("ullAvailVirtual", ctypes.c_ulonglong),
                            ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ]

                def __init__(self):
                    # Initialize this to the size of MEMORYSTATUSEX
                    self.dwLength = 2 * 4 + 7 * 8  # size = 2 ints, 7 longs
                    return super(MEMORYSTATUSEX, self).__init__()

            stat = MEMORYSTATUSEX()
            ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
            hardware_memory_total = str(stat.ullTotalPhys / 1024 ** 2) + " MB"
            hardware_memory_free = str(stat.ullAvailPhys / 1024 ** 2) + " MB"
        except:
            hardware_memory_total = ""
            hardware_memory_free = ""

        try:
            current_folder = os.path.split(os.path.realpath(sys.argv[0]))[0]
            _, disk_total, disk_free = ctypes.c_int64(), ctypes.c_int64(), \
                                       ctypes.c_int64()
            ret = ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                unicode(current_folder), ctypes.byref(_),
                ctypes.byref(disk_total), ctypes.byref(disk_free))
            hardware_disk_space_total = str(disk_total.value / 1024 ** 2) + " MB"
            hardware_disk_space_free = str(disk_free.value / 1024 ** 2) + " MB"
        except:
            hardware_disk_space_total = ""
            hardware_disk_space_free = ""

        try:
            tmp = str(_get_registry_value("HKEY_LOCAL_MACHINE",
                                          "HARDWARE\\DEVICEMAP\\VIDEO",
                                          "\Device\Video0"))
            idx = tmp.find("System")
            card = str(_get_registry_value("HKEY_LOCAL_MACHINE",
                                           tmp[idx:].replace("\\", "\\\\"),
                                           "Device Description"))
            hardware_video_card = card
        except:
            hardware_video_card = ""

        hardware_audio_card = ""  # TODO

    # Get platform specific info for OS X
    elif sys.platform.startswith("darwin"):
        os_platform = "Darwin"
        os_name = "Mac OS X"
        os_details = platform.mac_ver()[1][1]
        os_version = platform.mac_ver()[0]
        try:
            proc = subprocess.Popen(['sysctl', '-a', 'hw.model'],
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            hardware_cpu_details = \
                    proc.stdout.readline().split(":")[1].strip()
        except:
            hardware_cpu_details = ""
        try:
            proc = subprocess.Popen(['sysctl', '-a', 'hw.memsize'],
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            mem_total = int(proc.stdout.readline().split(":")[1].strip()) / 1024 ** 2
            hardware_memory_total = str(mem_total) + " MB"
        except:
            hardware_memory_total = ""

        try:
            import re
            proc = subprocess.Popen(['vm_stat'],
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            output = proc.stdout.read().split("\n")
            for item in output:
                x = item.find("Pages active:")
                y = item.find("page size of")
                if x > -1:
                    non_decimal = re.compile(r'[^\d.]+')
                    active = int(non_decimal.sub('', item).strip("."))
                if y > -1:
                    non_decimal = re.compile(r'[^\d.]+')
                    page = int(non_decimal.sub('', item).strip("."))
            hardware_memory_free = str(mem_total - (active * page) / 1024 ** 2) + " MB"

        except:
            hardware_memory_free = ""

        try:
            current_folder = os.path.split(os.path.realpath(sys.argv[0]))[0]
            s = os.statvfs(current_folder)
            disk_total = int((s.f_frsize * s.f_blocks) / 1024 ** 2)
            disk_free = int((s.f_frsize * s.f_bavail) / 1024 ** 2)
            hardware_disk_space_total = str(disk_total) + " MB"
            hardware_disk_space_free = str(disk_free) + " MB"
        except:
            hardware_disk_space_total = ""
            hardware_disk_space_free = ""

        try:
            proc = subprocess.Popen(['system_profiler', 'SPAudioDataType'],
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            hardware_audio_card = \
                proc.stdout.read().split("\n")[2].strip(":").strip()
        except:
            hardware_audio_card = ""

        try:
            import plistlib
            proc = subprocess.Popen(['system_profiler', 'SPDisplaysDataType',
                                     '-xml'],
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            pl = plistlib.readPlist(proc.stdout)
            hardware_video_card = []
            for card in pl[0]['_items']:
                hardware_video_card.append(card['sppci_model'])
        except:
            hardware_video_card = ""

    # Fill in info
    info["os_architecture"] = platform.architecture()[0]
    info["os_name"] = os_name
    info["os_details"] = os_details
    info["os_platform"] = os_platform
    info["os_release"] = platform.release()
    info["os_version"] = os_version
    info["settings_folder"] = expyriment._importer_functions.get_settings_folder()
    info["python_expyriment_build_date"] = __date__
    info["python_expyriment_revision"] = __revision__
    info["python_expyriment_version"] = __version__
    if _numpy is not None:
        numpy_version = _numpy.version.version
    else:
        numpy_version = ""
    info["python_numpy_version"] = numpy_version
    if _pil is not None:
        pil_version = _pil.VERSION
    else:
        pil_version = ""
    info["python_pil_version"] = pil_version
    info["python_pygame_version"] = pygame.version.ver
    if _ogl is not None:
        pyopengl_version = _ogl.version.__version__
    else:
        pyopengl_version = ""
    info["python_pyopengl_version"] = pyopengl_version
    if _parallel is not None:
        parallel_version = _parallel.VERSION
    else:
        parallel_version = ""
    info["python_pyparallel_version"] = parallel_version
    if _serial is not None:
        serial_version = _serial.VERSION
    else:
        serial_version = ""
    info["python_pyserial_version"] = serial_version
    info["python_version"] = "{0}.{1}.{2}".format(sys.version_info[0],
                                                  sys.version_info[1],
                                                  sys.version_info[2])

    info["hardware_audio_card"] = hardware_audio_card
    info["hardware_cpu_architecture"] = platform.machine()
    info["hardware_cpu_details"] = hardware_cpu_details
    info["hardware_cpu_type"] = platform.processor()
    info["hardware_disk_space_free"] = hardware_disk_space_free
    info["hardware_disk_space_total"] = hardware_disk_space_total
    try:
        socket.gethostbyname("expyriment.googlecode.com")
        hardware_internet_connection = "Yes"
    except:
        hardware_internet_connection = "No"
    info["hardware_internet_connection"] = hardware_internet_connection
    info["hardware_memory_total"] = hardware_memory_total
    info["hardware_memory_free"] = hardware_memory_free
    info["hardware_ports_parallel"] = \
            expyriment.io.ParallelPort.get_available_ports()
    info["hardware_ports_serial"] = \
            expyriment.io.SerialPort.get_available_ports()
    info["hardware_video_card"] = hardware_video_card

    if as_string:
        sorted_keys = info.keys()
        sorted_keys.sort()
        rtn = ""
        for key in sorted_keys:
            tabs = "\t" * (4 - int((len(key) + 1) / 8))
            try:
                rtn += key + ":" + tabs + info[key] + "\n"
            except TypeError:
                rtn += key + ":" + tabs + repr(info[key]) + "\n"
    else:
        rtn = info

    return rtn

Example 45

Project: pyzmq
Source File: setup.py
View license
    def run(self):
        cfg = self.config
        
        if cfg['libzmq_extension']:
            self.bundle_libzmq_extension()
            self.finish_run()
            return
        
        # When cross-compiling and zmq is given explicitly, we can't testbuild
        # (as we can't testrun the binary), we assume things are alright.
        if cfg['skip_check_zmq'] or self.cross_compiling:
            warn("Skipping zmq version check")
            self.finish_run()
            return
        
        zmq_prefix = cfg['zmq_prefix']
        # There is no available default on Windows, so start with fallback unless
        # zmq was given explicitly, or libzmq extension was explicitly prohibited.
        if sys.platform.startswith("win") and \
                not cfg['no_libzmq_extension'] and \
                not zmq_prefix:
            self.fallback_on_bundled()
            self.finish_run()
            return
        
        if zmq_prefix and self.bundle_libzmq_dylib and not sys.platform.startswith('win'):
            copy_and_patch_libzmq(zmq_prefix, libzmq_name+lib_ext)
        
        # first try with given config or defaults
        try:
            self.check_zmq_version()
        except LibZMQVersionError as e:
            info("\nBad libzmq version: %s\n" % e)
        except Exception as e:
            # print the error as distutils would if we let it raise:
            info("\nerror: %s\n" % e)
        else:
            self.finish_run()
            return
        
        # try fallback on /usr/local on *ix if no prefix is given
        if not zmq_prefix and not sys.platform.startswith('win'):
            info("Failed with default libzmq, trying again with /usr/local")
            time.sleep(1)
            zmq_prefix = cfg['zmq_prefix'] = '/usr/local'
            self.init_settings_from_config()
            try:
                self.check_zmq_version()
            except LibZMQVersionError as e:
                info("\nBad libzmq version: %s\n" % e)
            except Exception as e:
                # print the error as distutils would if we let it raise:
                info("\nerror: %s\n" % e)
            else:
                # if we get here the second run succeeded, so we need to update compiler
                # settings for the extensions with /usr/local prefix
                self.finish_run()
                return
        
        # finally, fallback on bundled
        
        if cfg['no_libzmq_extension']:
            fatal("Falling back on bundled libzmq,"
            " but config has explicitly prohibited building the libzmq extension."
            )
        
        self.fallback_on_bundled()
        
        self.finish_run()

Example 46

Project: PyFITS
Source File: hdulist.py
View license
    def _flush_resize(self):
        """
        Implements flushing changes in update mode when parts of one or more HDU
        need to be resized.
        """

        old_name = self._file.name
        old_memmap = self._file.memmap
        name = _tmp_name(old_name)

        if not self._file.file_like:
            old_mode = os.stat(old_name).st_mode
            # The underlying file is an actual file object.  The HDUList is
            # resized, so we need to write it to a tmp file, delete the
            # original file, and rename the tmp file to the original file.
            if self._file.compression == 'gzip':
                new_file = gzip.GzipFile(name, mode='ab+')
            elif self._file.compression == 'bzip2':
                new_file = bz2.BZ2File(name, mode='w')
            else:
                new_file = name

            hdulist = self.fromfile(new_file, mode='append')

            for hdu in self:
                hdu._writeto(hdulist._file, inplace=True, copy=True)

            if sys.platform.startswith('win'):
                # Collect a list of open mmaps to the data; this well be used
                # later.  See below.
                mmaps = [(idx, _get_array_mmap(hdu.data), hdu.data)
                         for idx, hdu in enumerate(self) if hdu._has_data]

            hdulist._file.close()
            self._file.close()

            if sys.platform.startswith('win'):
                # Close all open mmaps to the data.  This is only necessary on
                # Windows, which will not allow a file to be renamed or deleted
                # until all handles to that file have been closed.
                for idx, mmap, arr in mmaps:
                    if mmap is not None:
                        mmap.close()

            os.remove(self._file.name)

            # reopen the renamed new file with "update" mode
            os.rename(name, old_name)
            os.chmod(old_name, old_mode)

            if isinstance(new_file, gzip.GzipFile):
                old_file = gzip.GzipFile(old_name, mode='rb+')
            else:
                old_file = old_name

            ffo = _File(old_file, mode='update', memmap=old_memmap)

            self._file = ffo

            for hdu in self:
                # Need to update the _file attribute and close any open mmaps
                # on each HDU
                if hdu._has_data and _get_array_mmap(hdu.data) is not None:
                    del hdu.data
                hdu._file = ffo

            if sys.platform.startswith('win'):
                # On Windows, all the original data mmaps were closed above.
                # However, it's possible that the user still has references to
                # the old data which would no longer work (possibly even cause
                # a segfault if they try to access it).  This replaces the
                # buffers used by the original arrays with the buffers of mmap
                # arrays created from the new file.  This seems to work, but
                # it's a flaming hack and carries no guarantees that it won't
                # lead to odd behavior in practice.  Better to just not keep
                # references to data from files that had to be resized upon
                # flushing (on Windows--again, this is no problem on Linux).
                for idx, mmap, arr in mmaps:
                    if mmap is not None:
                        arr.data = self[idx].data.data
                del mmaps  # Just to be sure

        else:
            # The underlying file is not a file object, it is a file like
            # object.  We can't write out to a file, we must update the file
            # like object in place.  To do this, we write out to a temporary
            # file, then delete the contents in our file like object, then
            # write the contents of the temporary file to the now empty file
            # like object.
            self.writeto(name)
            hdulist = self.fromfile(name)
            ffo = self._file

            ffo.truncate(0)
            ffo.seek(0)

            for hdu in hdulist:
                hdu._writeto(ffo, inplace=True, copy=True)

            # Close the temporary file and delete it.
            hdulist.close()
            os.remove(hdulist._file.name)

        # reset the resize attributes after updating
        self._resize = False
        self._truncate = False
        for hdu in self:
            hdu._header._modified = False
            hdu._new = False
            hdu._file = ffo

Example 47

Project: neuroConstruct
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        open(TESTFN, "wb").write("a"*mapsize)
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")

        # Ensuring that readonly mmap can't be slice assigned
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be item assigned
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write() to
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write_byte() to
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be resized
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            self.fail("Able to resize readonly memory map")
        f.close()
        del m, f
        self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
               "Readonly memory map data file was modified")

        # Opening mmap with size too big
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        # Opening mmap with access=ACCESS_WRITE
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        # Modifying write-through memory map
        m[:] = 'c'*mapsize
        self.assertEqual(m[:], 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        self.assertEqual(stuff, 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        # Modifying copy-on-write memory map
        m[:] = 'd'*mapsize
        self.assertEqual(m[:], 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        # Ensuring copy-on-write maps cannot be resized
        self.assertRaises(TypeError, m.resize, 2*mapsize)
        f.close()
        del m, f

        # Ensuring invalid access parameter raises exception
        f = open(TESTFN, "r+b")
        self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
        f.close()

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                              flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            f.close()

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 48

Project: neuroConstruct
Source File: test_mmap.py
View license
    def test_access_parameter(self):
        # Test for "access" keyword parameter
        mapsize = 10
        open(TESTFN, "wb").write("a"*mapsize)
        f = open(TESTFN, "rb")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
        self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")

        # Ensuring that readonly mmap can't be slice assigned
        try:
            m[:] = 'b'*mapsize
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be item assigned
        try:
            m[0] = 'b'
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write() to
        try:
            m.seek(0,0)
            m.write('abc')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be write_byte() to
        try:
            m.seek(0,0)
            m.write_byte('d')
        except TypeError:
            pass
        else:
            self.fail("Able to write to readonly memory map")

        # Ensuring that readonly mmap can't be resized
        try:
            m.resize(2*mapsize)
        except SystemError:   # resize is not universally supported
            pass
        except TypeError:
            pass
        else:
            self.fail("Able to resize readonly memory map")
        f.close()
        del m, f
        self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
               "Readonly memory map data file was modified")

        # Opening mmap with size too big
        import sys
        f = open(TESTFN, "r+b")
        try:
            m = mmap.mmap(f.fileno(), mapsize+1)
        except ValueError:
            # we do not expect a ValueError on Windows
            # CAUTION:  This also changes the size of the file on disk, and
            # later tests assume that the length hasn't changed.  We need to
            # repair that.
            if sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should work on Windows.")
        else:
            # we expect a ValueError on Unix, but not on Windows
            if not sys.platform.startswith('win'):
                self.fail("Opening mmap with size+1 should raise ValueError.")
            m.close()
        f.close()
        if sys.platform.startswith('win'):
            # Repair damage from the resizing test.
            f = open(TESTFN, 'r+b')
            f.truncate(mapsize)
            f.close()

        # Opening mmap with access=ACCESS_WRITE
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
        # Modifying write-through memory map
        m[:] = 'c'*mapsize
        self.assertEqual(m[:], 'c'*mapsize,
               "Write-through memory map memory not updated properly.")
        m.flush()
        m.close()
        f.close()
        f = open(TESTFN, 'rb')
        stuff = f.read()
        f.close()
        self.assertEqual(stuff, 'c'*mapsize,
               "Write-through memory map data file not updated properly.")

        # Opening mmap with access=ACCESS_COPY
        f = open(TESTFN, "r+b")
        m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
        # Modifying copy-on-write memory map
        m[:] = 'd'*mapsize
        self.assertEqual(m[:], 'd' * mapsize,
               "Copy-on-write memory map data not written correctly.")
        m.flush()
        self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
               "Copy-on-write test data file should not be modified.")
        # Ensuring copy-on-write maps cannot be resized
        self.assertRaises(TypeError, m.resize, 2*mapsize)
        f.close()
        del m, f

        # Ensuring invalid access parameter raises exception
        f = open(TESTFN, "r+b")
        self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
        f.close()

        if os.name == "posix":
            # Try incompatible flags, prot and access parameters.
            f = open(TESTFN, "r+b")
            self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
                              flags=mmap.MAP_PRIVATE,
                              prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
            f.close()

            # Try writing with PROT_EXEC and without PROT_WRITE
            prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
            with open(TESTFN, "r+b") as f:
                m = mmap.mmap(f.fileno(), mapsize, prot=prot)
                self.assertRaises(TypeError, m.write, b"abcdef")
                self.assertRaises(TypeError, m.write_byte, 0)
                m.close()

Example 49

Project: jhbuild
Source File: environment.py
View license
def addpath(envvar, path, prepend=True):
    '''Adds a path to an environment variable.'''
    if envvar in [ 'LDFLAGS', 'CFLAGS', 'CXXFLAGS' ]:
        if sys.platform.startswith('win'):
            path = subprocess_win32.fix_path_for_msys(path)

        envval = os.environ.get(envvar)
        if envval:
            envval = path + ' ' + envval
        else:
            envval = path
    else:
        if envvar == 'PATH':
            # PATH is special cased on Windows to allow execution without
            # sh.exe. The other env vars (like LD_LIBRARY_PATH) don't mean
            # anything to native Windows so they stay in UNIX format, but
            # PATH is kept in Windows format (; separated, c:/ or c:\ format
            # paths) so native Popen works.
            pathsep = os.pathsep
        else:
            pathsep = ':'
            if sys.platform.startswith('win'):
                path = subprocess_win32.fix_path_for_msys(path)

            if sys.platform.startswith('win') and len(path) > 1 and \
               path[1] == ':':
                # Windows: Don't allow c:/ style paths in :-separated env vars
                # for obvious reasons. /c/ style paths are valid - if a var is
                # separated by : it will only be of interest to programs inside
                # MSYS anyway.
                path='/'+path[0]+path[2:]

        envval = os.environ.get(envvar, path)
        parts = envval.split(pathsep)
        if prepend:
            parts.insert(0, path)
        else:
            parts.append(path)
        # remove duplicate entries:
        i = 1
        while i < len(parts):
            if parts[i] in parts[:i]:
                del parts[i]
            elif envvar == 'PYTHONPATH' and parts[i] == "":
                del parts[i]
            else:
                i += 1
        envval = pathsep.join(parts)

    os.environ[envvar] = envval

Example 50

Project: flexx
Source File: gllib.py
View license
    def _load_lib(self):
        _lib = ''  # os.getenv('XXX', '')
        need_es2 = False
        
        if _lib != '':
            # Force a library
            if sys.platform.startswith('win'):
                _lib = ctypes.windll.LoadLibrary(_lib)
            else:
                _lib = ctypes.cdll.LoadLibrary(_lib)
        
        elif need_es2:
            # ES2 lib
            es2_file = None
            if 'ES2_LIBRARY' in os.environ:  # todo: is this the correct name?
                if os.path.exists(os.environ['ES2_LIBRARY']):
                    es2_file = os.path.realpath(os.environ['ES2_LIBRARY'])
            if es2_file is None:
                es2_file = ctypes.util.find_library('GLESv2')
            if es2_file is None:
                raise OSError('GL ES 2.0 library not found')
            _lib = ctypes.CDLL(es2_file)
        
        elif sys.platform.startswith('win'):
            # Windows
            _lib = ctypes.windll.opengl32
            try:
                wglGetProcAddress = _lib.wglGetProcAddress
                wglGetProcAddress.restype = ctypes.CFUNCTYPE(
                    ctypes.POINTER(ctypes.c_int))
                wglGetProcAddress.argtypes = [ctypes.c_char_p]
                self._have_get_proc_address = True
            except AttributeError:
                pass
        
        else:
            # Unix-ish
            if sys.platform.startswith('darwin'):
                _fname = ctypes.util.find_library('OpenGL')
            else:
                _fname = ctypes.util.find_library('GL')
            if not _fname:
                raise RuntimeError('Could not load OpenGL library.')
            # Load lib
            _lib = ctypes.cdll.LoadLibrary(_fname)
        
        self._lib = _lib