Example #1
0
    def captureException(self, exception, value, tb):
        from .local_server import LocalServer
        from .local_config import LocalConfig
        from .controller import Controller
        from .compute_manager import ComputeManager

        local_server = LocalServer.instance().localServerSettings()
        if local_server["report_errors"]:
            if not RAVEN_AVAILABLE:
                return

            if os.path.exists(LocalConfig.instance().runAsRootPath()):
                log.warning("User has run application as root. Crash reports are disabled.")
                sys.exit(1)
                return

            if os.path.exists(".git"):
                log.warning("A .git directory exist crash report is turn off for developers. Instant exit")
                sys.exit(1)
                return

            if hasattr(exception, "fingerprint"):
                client = raven.Client(CrashReport.DSN, release=__version__, fingerprint=['{{ default }}', exception.fingerprint], transport=HTTPTransport)
            else:
                client = raven.Client(CrashReport.DSN, release=__version__, transport=HTTPTransport)
            context = {
                "os:name": platform.system(),
                "os:release": platform.release(),
                "os:win_32": " ".join(platform.win32_ver()),
                "os:mac": "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2]),
                "os:linux": " ".join(distro.linux_distribution()),
                "python:version": "{}.{}.{}".format(sys.version_info[0],
                                                    sys.version_info[1],
                                                    sys.version_info[2]),
                "python:bit": struct.calcsize("P") * 8,
                "python:encoding": sys.getdefaultencoding(),
                "python:frozen": "{}".format(hasattr(sys, "frozen")),
            }

            # extra controller and compute information
            extra_context = {"controller:version": Controller.instance().version(),
                             "controller:host": Controller.instance().host(),
                             "controller:connected": Controller.instance().connected()}
            for index, compute in enumerate(ComputeManager.instance().computes()):
                extra_context["compute{}:id".format(index)] = compute.id()
                extra_context["compute{}:name".format(index)] = compute.name(),
                extra_context["compute{}:host".format(index)] = compute.host(),
                extra_context["compute{}:connected".format(index)] = compute.connected()
                extra_context["compute{}:platform".format(index)] = compute.capabilities().get("platform")
                extra_context["compute{}:version".format(index)] = compute.capabilities().get("version")

            context = self._add_qt_information(context)
            client.tags_context(context)
            client.extra_context(extra_context)
            try:
                report = client.captureException((exception, value, tb))
            except Exception as e:
                log.error("Can't send crash report to Sentry: {}".format(e))
                return
            log.debug("Crash report sent with event ID: {}".format(client.get_ident(report)))
def main():
    colorama.init()

    parser = argparse.ArgumentParser(description="build a blenderseed package from sources")

    parser.add_argument("--nozip", action="store_true", help="copies appleseed binaries to blenderseed folder but does not build a release package")

    args = parser.parse_args()

    no_release = args.nozip
    package_version = subprocess.Popen("git describe --long", stdout=subprocess.PIPE, shell=True).stdout.read().strip()

    build_date = datetime.date.today().isoformat()

    print("blenderseed.package version " + VERSION)
    print("")

    settings = Settings()
    settings.load()
    settings.print_summary()

    if os.name == "nt":
        package_builder = WindowsPackageBuilder(settings, package_version, build_date, no_release)
    elif os.name == "posix" and platform.mac_ver()[0] != "":
        package_builder = MacPackageBuilder(settings, package_version, build_date, no_release)
    elif os.name == "posix" and platform.mac_ver()[0] == "":
        package_builder = LinuxPackageBuilder(settings, package_version, build_date, no_release)
    else:
        fatal("Unsupported platform: " + os.name)

    package_builder.build_package()
Example #3
0
    def finishLaunching(self):
        self.connection = False
        statusbar = AppKit.NSStatusBar.systemStatusBar()
        self.statusitem = statusbar.statusItemWithLength_(AppKit.NSVariableStatusItemLength)
        self.icon = AppKit.NSImage.alloc().initByReferencingFile_(ICON_PATH)
        self.icon.setScalesWhenResized_(True)
        self.icon.setSize_((20, 20))
        self.statusitem.setImage_(self.icon)
        self.menubarMenu = AppKit.NSMenu.alloc().init()
        self.open = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Open", "openui:", "")
        self.menubarMenu.addItem_(self.open)
        self.quit = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Quit", "replyToApplicationShouldTerminate:", "")
        self.menubarMenu.addItem_(self.quit)
        self.statusitem.setMenu_(self.menubarMenu)
        self.statusitem.setToolTip_(APP_NAME)


        if test_internet_connection():
            if platform.mac_ver()[0] >= "10.10":
                LBRYNotify("Starting LBRY")
        else:
            if platform.mac_ver()[0] >= "10.10":
                LBRYNotify("LBRY needs an internet connection to start, try again when one is available")
            sys.exit(0)

        # if not subprocess.check_output("git ls-remote https://github.com/lbryio/lbry-web-ui.git | grep HEAD | cut -f 1",
        #                                shell=True):
        #     LBRYNotify(
        #         "You should have been prompted to install xcode command line tools, please do so and then start LBRY")
        #     sys.exit(0)

        lbry = LBRYDaemonServer()
        d = lbry.start()
        d.addCallback(lambda _: webbrowser.open(UI_ADDRESS))
        reactor.listenTCP(API_PORT, server.Site(lbry.root), interface=API_INTERFACE)
Example #4
0
def get_env_info():
    '''Gets general information about the computer.'''
    
    infodict = OrderedDict()
    
    infodict["Name"] = platform.node()
    infodict["System"] = platform.system()
    infodict["System alias"] = " ".join(platform.system_alias(
            platform.system(), platform.release(), platform.version()))
    infodict["Platform"] = platform.platform()
    
    if infodict["System"] == "Linux": # System-specific information
        infodict["Distribution"] = " ".join(platform.dist())
    elif infodict["System"] == "Windows":
        infodict["OS"] = " ".join(platform.win32_ver())
    elif infodict["System"] == "MacOS":
        verinfo = platform.mac_ver()[1]
        macver = " ".join(platform.mac_ver())
        macver[1] = verinfo
        infodict["OS"] = " ".join(macver)
    
    infodict["Boot time"] = datetime.datetime.fromtimestamp(
            psutil.get_boot_time()).strftime("%c")
    infodict["Uptime"] = str(datetime.datetime.fromtimestamp(
            time.time() - psutil.get_boot_time()).strftime("%d:%H:%M:%S:%f"))
    
    for user in psutil.get_users():
        infodict["User '" + user.name + "' terminal"] = user.terminal
        infodict["User '" + user.name + "' host"] = user.host
        infodict["User '" + user.name + "' started"] = str(
                datetime.datetime.fromtimestamp(user.started).strftime("%c"))
    
    return infodict
Example #5
0
  def __init__(self, cache_dir, verbose=False):
    if not platform.platform().startswith("Darwin"):
      raise Exception("Only supported on OSX.")

    self.cache_dir = cache_dir

    # Sanity check: are we on a platform we understand?
    if platform.mac_ver()[0].startswith('10.6'):
      self.ver = 21
    elif platform.mac_ver()[0].startswith('10.7'):
      self.ver = 25
    else:
      raise Exception("Unrecognized OSX version: %s" % platform.mac_ver())

    # Sanity check: does cc exist?
    if not os.path.exists("/usr/bin/cc"):
      raise CompilerNeededException()

    # look the result in build dir
    if not os.path.exists(os.path.join(cache_dir, "libutil-%s" % self.ver, "libutil1.0.dylib")):
      self._download_and_compile(verbose)
      self.did_compile = True
    else:
      self.did_compile = False
    assert os.path.exists(os.path.join(cache_dir, "libutil-%s" % self.ver, "libutil1.0.dylib"))
    def capture_exception(self, exception, value, tb):
        if not RAVEN_AVAILABLE:
            return
        report_errors = True
        if report_errors:
            if self._client is None:
                self._client = raven.Client(CrashReport.DSN,
                                            release=__version__)

            tags = {"os:name": platform.system(),
                    "os:release": platform.release(),
                    "python:version": "{}.{}.{}".format(sys.version_info[0],
                                                    sys.version_info[1],
                                                    sys.version_info[2]),
                    "python:bit": struct.calcsize("P") * 8,
                    "python:encoding": sys.getdefaultencoding(),
                    "python:frozen": "{}".format(hasattr(sys, "frozen"))}

            if sys.platform == 'win32':
                tags['os:win32'] = " ".join(platform.win32_ver())
            elif sys.platform == 'darwin':
                tags['os:mac'] = "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2])
            else:
                tags['os:linux'] = " ".join(platform.linux_distribution())

            self._client.tags_context(tags)
            try:
                report = self._client.captureException((exception, value, tb))
            except Exception as e:
                log.error("Can't send crash report to Sentry: {}".format(e))
                return
            log.info("Crash report sent with event ID: {}".format(
                self._client.get_ident(report)))
Example #7
0
def drop(work_dir, new_uid='root', new_gid='root'):
    starting_uid = os.getuid()
    starting_gid = os.getgid()

    if os.getuid() != 0:
        return
    if starting_uid == 0:

        #special handling for os x < 10.9. (getgrname has trouble with gid below 0)
        if platform.mac_ver()[0] and platform.mac_ver()[0] < float('10.9'):
            wanted_gid = -2
        else:
            wanted_gid = grp.getgrnam(new_gid)[2]

        run_uid = pwd.getpwnam(new_uid)[2]
        run_gid = wanted_gid
        try:
            recursive_chown(work_dir, run_uid, run_gid)
        except OSError as e:
            logger.exception("Could not change file owner: {0}".format(e))
        try:
            os.setgid(run_gid)
        except OSError as e:
            logger.exception("Could not set new group: {0}".format(e))

        try:
            os.setuid(run_uid)
        except OSError as e:
            logger.exception("Could not set net user: {0}".format(e))

        new_umask = 066
        try:
            os.umask(new_umask)
        except Exception as e:
            logger.error("Failed to change umask: {0}".format(e))
Example #8
0
    def finishLaunching(self):
        self.connection = False
        statusbar = AppKit.NSStatusBar.systemStatusBar()
        self.statusitem = statusbar.statusItemWithLength_(AppKit.NSVariableStatusItemLength)
        self.icon = AppKit.NSImage.alloc().initByReferencingFile_(ICON_PATH)
        self.icon.setScalesWhenResized_(True)
        self.icon.setSize_((20, 20))
        self.statusitem.setImage_(self.icon)
        self.menubarMenu = AppKit.NSMenu.alloc().init()
        self.open = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Open", "openui:", "")
        self.menubarMenu.addItem_(self.open)
        self.quit = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            "Quit", "replyToApplicationShouldTerminate:", ""
        )
        self.menubarMenu.addItem_(self.quit)
        self.statusitem.setMenu_(self.menubarMenu)
        self.statusitem.setToolTip_(APP_NAME)

        if test_internet_connection():
            if platform.mac_ver()[0] >= "10.10":
                LBRYNotify("Starting LBRY")
        else:
            if platform.mac_ver()[0] >= "10.10":
                LBRYNotify("LBRY needs an internet connection to start, try again when one is available")
            sys.exit(0)

        lbry = DaemonServer()
        d = lbry.start()
        d.addCallback(lambda _: webbrowser.open(UI_ADDRESS))
        lbrynet_server = server.Site(lbry.root)
        lbrynet_server.requestFactory = DaemonRequest
        reactor.listenTCP(API_PORT, lbrynet_server, interface=API_INTERFACE)
 def capture_exception(self, request=None):
     if not RAVEN_AVAILABLE:
         return
     if os.path.exists(".git"):
         log.warning("A .git directory exist crash report is turn off for developers")
         return
     server_config = Config.instance().get_section_config("Server")
     if server_config.getboolean("report_errors"):
         if self._client is None:
             self._client = raven.Client(CrashReport.DSN, release=__version__, raise_send_errors=True)
         if request is not None:
             self._client.http_context({
                 "method": request.method,
                 "url": request.path,
                 "data": request.json,
             })
         self._client.tags_context({
             "os:name": platform.system(),
             "os:release": platform.release(),
             "os:win_32": " ".join(platform.win32_ver()),
             "os:mac": "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2]),
             "os:linux": " ".join(platform.linux_distribution()),
             "python:version": "{}.{}.{}".format(sys.version_info[0],
                                                 sys.version_info[1],
                                                 sys.version_info[2]),
             "python:bit": struct.calcsize("P") * 8,
             "python:encoding": sys.getdefaultencoding(),
             "python:frozen": "{}".format(hasattr(sys, "frozen"))
         })
         try:
             report = self._client.captureException()
         except Exception as e:
             log.error("Can't send crash report to Sentry: {}".format(e))
             return
         log.info("Crash report sent with event ID: {}".format(self._client.get_ident(report)))
def main():
    parser = argparse.ArgumentParser(description="build an appleseed package from sources")

    parser.add_argument("--nozip", help="do not build a final .zip.  Files will be copied to staging directory only", action="store_true")

    args = parser.parse_args()

    no_zip = args.nozip

    print("appleseed.package version " + VERSION)
    print("")

    print("IMPORTANT:")
    print("")
    print("  - You may need to run this tool with sudo on Linux and macOS")
    print("  - Make sure there are no obsolete binaries in sandbox/bin")
    print("")

    settings = Settings()
    package_info = PackageInfo(settings, no_zip)

    settings.load()
    package_info.load()

    if os.name == "nt":
        package_builder = WindowsPackageBuilder(settings, package_info)
    elif os.name == "posix" and platform.mac_ver()[0] != "":
        package_builder = MacPackageBuilder(settings, package_info)
    elif os.name == "posix" and platform.mac_ver()[0] == "":
        package_builder = LinuxPackageBuilder(settings, package_info)
    else:
        fatal("Unsupported platform: " + os.name)

    package_builder.build_package()
Example #11
0
 def captureException(self, exception, value, tb):
     if not RAVEN_AVAILABLE:
         return
     if os.path.exists(".git"):
         log.warning("A .git directory exist crash report is turn off for developers")
         return
     local_server = Servers.instance().localServerSettings()
     if local_server["report_errors"]:
         if self._client is None:
             self._client = raven.Client(CrashReport.DSN, release=__version__)
         self._client.tags_context({
             "os:name": platform.system(),
             "os:release": platform.release(),
             "os:win_32": " ".join(platform.win32_ver()),
             "os:mac": "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2]),
             "os:linux": " ".join(platform.linux_distribution()),
             "python:version": "{}.{}.{}".format(sys.version_info[0],
                                                 sys.version_info[1],
                                                 sys.version_info[2]),
             "python:bit": struct.calcsize("P") * 8,
             "python:encoding": sys.getdefaultencoding(),
             "python:frozen": "{}".format(hasattr(sys, "frozen"))
         })
         try:
             report = self._client.captureException((exception, value, tb))
         except Exception as e:
             log.error("Can't send crash report to Sentry: {}".format(e))
             return
         log.info("Crash report sent with event ID: {}".format(self._client.get_ident(report)))
Example #12
0
def get_system_type():
    print platform.system()
    print platform.machine()
    print platform.mac_ver()
    print platform.win32_ver()
    print platform.linux_distribution()
    print platform.platform()
Example #13
0
def main():
    print("appleseed.package version " + VERSION)
    print("")

    print("IMPORTANT:")
    print("")
    print("  - You may need to run this tool with sudo on Linux and macOS")
    print("  - Make sure there are no obsolete binaries in sandbox/bin")
    print("")

    settings = Settings()
    package_info = PackageInfo(settings)

    settings.load()
    package_info.load()

    if os.name == "nt":
        package_builder = WindowsPackageBuilder(settings, package_info)
    elif os.name == "posix" and platform.mac_ver()[0] != "":
        package_builder = MacPackageBuilder(settings, package_info)
    elif os.name == "posix" and platform.mac_ver()[0] == "":
        package_builder = LinuxPackageBuilder(settings, package_info)
    else:
        fatal("Unsupported platform: " + os.name)

    package_builder.build_package()
Example #14
0
def format_platform_info():
    platform_info = [
        'architecture: %s %s\n' % platform.architecture(),
        'machine: %s\n' % platform.machine(),
        'platform: %s\n' % platform.platform(),
    ]
    libc_ver = '%s: %s\n' % platform.libc_ver()
    if libc_ver.strip():
        platform_info.append(libc_ver)

    if platform.dist() != ('', '', ''):
        platform_info.append('GNU/Linux: %s\n' % ' '.join(platform.dist()))
    elif platform.mac_ver() != ('', ('', '', ''), ''):
        platform_info.append('Mac OS X: %s\n' % platform.mac_ver()[0])
    elif platform.win32_ver() != ('', '', '', ''):
        platform_info.append('Windows: %s\n' % platform.win32_ver()[0])

    platform_info.append('python_compiler: %s\n' % platform.python_compiler())
    platform_info.append(
        'python_implementation: %s\n' % platform.python_implementation())

    platform_info.append('locale: %s\n' % (locale.getlocale(),))
    platform_info.append('default encoding: %s\n' % sys.getdefaultencoding())
    platform_info.append('file system encoding: %s\n' % sys.getfilesystemencoding())

    return platform_info
Example #15
0
def user_agent():
    """
    Return a string representing the user agent.
    """
    data = {
        "installer": {"name": "pip", "version": pip.__version__},
        "python": platform.python_version(),
        "implementation": {
            "name": platform.python_implementation(),
        },
    }

    if data["implementation"]["name"] == 'CPython':
        data["implementation"]["version"] = platform.python_version()
    elif data["implementation"]["name"] == 'PyPy':
        if sys.pypy_version_info.releaselevel == 'final':
            pypy_version_info = sys.pypy_version_info[:3]
        else:
            pypy_version_info = sys.pypy_version_info
        data["implementation"]["version"] = ".".join(
            [str(x) for x in pypy_version_info]
        )
    elif data["implementation"]["name"] == 'Jython':
        # Complete Guess
        data["implementation"]["version"] = platform.python_version()
    elif data["implementation"]["name"] == 'IronPython':
        # Complete Guess
        data["implementation"]["version"] = platform.python_version()

    if sys.platform.startswith("linux"):
        distro = dict(filter(
            lambda x: x[1],
            zip(["name", "version", "id"], platform.linux_distribution()),
        ))
        libc = dict(filter(
            lambda x: x[1],
            zip(["lib", "version"], platform.libc_ver()),
        ))
        if libc:
            distro["libc"] = libc
        if distro:
            data["distro"] = distro

    if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
        data["distro"] = {"name": "OS X", "version": platform.mac_ver()[0]}

    if platform.system():
        data.setdefault("system", {})["name"] = platform.system()

    if platform.release():
        data.setdefault("system", {})["release"] = platform.release()

    if platform.machine():
        data["cpu"] = platform.machine()

    return "{data[installer][name]}/{data[installer][version]} {json}".format(
        data=data,
        json=json.dumps(data, separators=(",", ":"), sort_keys=True),
    )
Example #16
0
 def get_os_release():
     """Returns detailed OS release."""
     if platform.linux_distribution()[0]:
         return " ".join(platform.linux_distribution())
     elif platform.mac_ver()[0]:
         return "%s %s" % (platform.mac_ver()[0], platform.mac_ver()[2])
     else:
         return "Unknown"
Example #17
0
    def capture_exception(self, request=None):
        if not RAVEN_AVAILABLE:
            return
        if os.path.exists(".git"):
            log.warning("A .git directory exist crash report is turn off for developers")
            return
        server_config = Config.instance().get_section_config("Server")
        if server_config.getboolean("report_errors"):
            if self._client is None:
                self._client = raven.Client(CrashReport.DSN, release=__version__, raise_send_errors=True, transport=HTTPTransport)
            if request is not None:
                self._client.http_context({
                    "method": request.method,
                    "url": request.path,
                    "data": request.json,
                })

            context = {
                "os:name": platform.system(),
                "os:release": platform.release(),
                "os:win_32": " ".join(platform.win32_ver()),
                "os:mac": "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2]),
                "os:linux": " ".join(distro.linux_distribution()),
                "aiohttp:version": aiohttp.__version__,
                "python:version": "{}.{}.{}".format(sys.version_info[0],
                                                    sys.version_info[1],
                                                    sys.version_info[2]),
                "python:bit": struct.calcsize("P") * 8,
                "python:encoding": sys.getdefaultencoding(),
                "python:frozen": "{}".format(hasattr(sys, "frozen"))
            }

            if sys.platform.startswith("linux") and not hasattr(sys, "frozen"):
                # add locale information
                try:
                    language, encoding = locale.getlocale()
                    context["locale:language"] = language
                    context["locale:encoding"] = encoding
                except ValueError:
                    pass

                # add GNS3 VM version if it exists
                home = os.path.expanduser("~")
                gns3vm_version = os.path.join(home, ".config", "GNS3", "gns3vm_version")
                if os.path.isfile(gns3vm_version):
                    try:
                        with open(gns3vm_version) as fd:
                            context["gns3vm:version"] = fd.readline().strip()
                    except OSError:
                        pass

            self._client.tags_context(context)
            try:
                report = self._client.captureException()
            except Exception as e:
                log.error("Can't send crash report to Sentry: {}".format(e))
                return
            log.info("Crash report sent with event ID: {}".format(self._client.get_ident(report)))
Example #18
0
 def name(self):
     platform = self._get_platform()
     if platform == Platforms.linux:
         return '-'.join(_platform.linux_distribution()[:2])
     if platform == Platforms.macosx:
         return '-'.join(['MacOS', _platform.mac_ver()[0], _platform.mac_ver()[-1]])
     if platform == Platforms.windows:
         return '-'.join(['Windows', _platform.win32_ver()[0]])
     return Platforms.unknown.name
Example #19
0
def diagnostic_info():
    """Return diagnostic information as a string"""
    s = "BleachBit version %s" % bleachbit.APP_VERSION
    try:
        import gtk
        s += '\nGTK version %s' % '.'.join([str(x) for x in gtk.gtk_version])
    except:
        pass
    s += "\nlocal_cleaners_dir = %s" % bleachbit.local_cleaners_dir
    s += "\nlocale_dir = %s" % bleachbit.locale_dir
    s += "\noptions_dir = %s" % bleachbit.options_dir.decode(bleachbit.FSE)
    s += "\npersonal_cleaners_dir = %s" % bleachbit.personal_cleaners_dir.decode(bleachbit.FSE)
    s += "\nsystem_cleaners_dir = %s" % bleachbit.system_cleaners_dir
    s += "\nlocale.getdefaultlocale = %s" % str(locale.getdefaultlocale())
    if 'posix' == os.name:
        envs = ('DESKTOP_SESSION', 'LOGNAME', 'USER', 'SUDO_UID')
    if 'nt' == os.name:
        envs = ('APPDATA', 'LocalAppData', 'LocalAppDataLow', 'Music',
                'USERPROFILE', 'ProgramFiles', 'ProgramW6432', 'TMP')
    for env in envs:
        if os.getenv(env):
            s += "\nos.getenv('%s') = %s" % (env, os.getenv(env).decode(bleachbit.FSE))
        else:
            s += "\nos.getenv('%s') = %s" % (env, os.getenv(env))
    s += "\nos.path.expanduser('~') = %s" % bleachbit.expanduser('~').decode(bleachbit.FSE)
    if sys.platform.startswith('linux'):
        if hasattr(platform, 'linux_distribution'):
            s += "\nplatform.linux_distribution() = %s" % str(
                platform.linux_distribution())
        else:
            s += "\nplatform.dist() = %s" % str(platform.dist())
            
    # Mac Version Name - Dictonary "masosx_dict"
    macosx_dict = {'5':'Lepoard','6':'Snow Lepoard','7':'Lion','8':'Mountain Lion','9':'Mavericks','10':'Yosemite','11':'El Capitan','12':'Sierra'}

    if sys.platform.startswith('darwin'):
        if hasattr(platform, 'mac_ver'):
            for key in macosx_dict:
                if (platform.mac_ver()[0].split('.')[1] == key):
                    s += "\nplatform.mac_ver() = %s" % str(
                        platform.mac_ver()[0] + " (" + macosx_dict[key] + ")")
        else:
            s += "\nplatform.dist() = %s" % str(platform.dist())

    if 'nt' == os.name:
        s += "\nplatform.win32_ver[1]() = %s" % platform.win32_ver()[1]
    s += "\nplatform.platform = %s" % platform.platform()
    s += "\nplatform.version = %s" % platform.version()
    s += "\nsys.argv = %s" % sys.argv
    s += "\nsys.executable = %s" % sys.executable
    s += "\nsys.version = %s" % sys.version
    if 'nt' == os.name:
        s += "\nwin32com.shell.shell.IsUserAnAdmin() = %s" % shell.IsUserAnAdmin(
        )
    s += "\n__file__ = %s" % __file__

    return s
Example #20
0
def platform_details():
    if sys.platform == "win32":
        return " ".join(platform.win32_ver())
    elif sys.platform == "darwin":
        return "{0} {1}".format(platform.mac_ver()[0], platform.mac_ver()[2])
    elif "linux" in sys.platform:
        return " ".join(platform.linux_distribution())
    else:
        return "Unknown OS"
Example #21
0
def get_dist():
    if platform.dist()[0]:
        return platform.dist()[0].lower()
    elif platform.mac_ver()[0]:
        darwin_version = platform.mac_ver()[0].rsplit('.', 1)[0]
        return 'darwin%s' % darwin_version
    elif platform.win32_ver()[0]:
        return platform.win32_ver()[0].lower()
    return 'unknown'
Example #22
0
def build_osx(config, basedir):
    version, simple_version = get_version(basedir)

    osxver    = platform.mac_ver()[0][:platform.mac_ver()[0].rindex('.')]
    framework = config.split('-')[1]
    if osxver == '10.6':
        osxcfg = '-%s -platform macx-g++42' % framework
    else:
        osxcfg = '-%s -platform unsupported/macx-clang' % framework

    flags = ''
    if framework == 'carbon' and osxver != '10.6':
        for item in ['CFLAGS', 'CXXFLAGS']:
            flags += '"QMAKE_%s += %s" ' % (item, '-fvisibility=hidden -fvisibility-inlines-hidden')

    qt     = os.path.join(basedir, config, 'qt')
    app    = os.path.join(basedir, config, 'app')
    dist   = os.path.join(basedir, config, 'wkhtmltox-%s' % version)

    mkdir_p(qt)
    mkdir_p(app)

    rmdir(dist)
    mkdir_p(os.path.join(dist, 'bin'))
    mkdir_p(os.path.join(dist, 'include', 'wkhtmltox'))
    mkdir_p(os.path.join(dist, 'lib'))

    os.chdir(qt)
    if not exists('is_configured'):
        shell('../../../qt/configure %s' % qt_config('osx', '--prefix=%s' % qt, osxcfg))
        shell('touch is_configured')

    shell('make -j%d' % CPU_COUNT)

    os.chdir(app)
    shell('rm -f bin/*')
    os.environ['WKHTMLTOX_VERSION'] = version
    shell('../qt/bin/qmake %s ../../../wkhtmltopdf.pro' % flags)
    shell('make -j%d' % CPU_COUNT)

    if osxver not in ['10.6', '10.7']:
        for item in ['wkhtmltoimage', 'wkhtmltopdf', 'libwkhtmltox.%s.dylib' % simple_version]:
            shell(' '.join([
                'install_name_tool', '-change',
                '/System/Library/Frameworks/CoreText.framework/Versions/A/CoreText',
                '/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreText.framework/CoreText',
                'bin/'+item]))

    shell('cp bin/wkhtmlto* ../wkhtmltox-%s/bin' % version)
    shell('cp -P bin/libwkhtmltox*.dylib* ../wkhtmltox-%s/lib' % version)
    shell('cp ../../../include/wkhtmltox/*.h ../wkhtmltox-%s/include/wkhtmltox' % version)
    shell('cp ../../../include/wkhtmltox/dll*.inc ../wkhtmltox-%s/include/wkhtmltox' % version)

    os.chdir(os.path.join(basedir, config))
    shell('tar -c -v -f ../wkhtmltox-%s_%s.tar wkhtmltox-%s/' % (version, config, version))
    shell('xz --compress --force --verbose -9 ../wkhtmltox-%s_%s.tar' % (version, config))
Example #23
0
def getOSVersion():
    try:
        if len(platform.mac_ver()[0]) > 0:
            version = "%s;%s" % (platform.platform(),
                                 platform.mac_ver()[0])
        else:
            version = platform.platform()
    except:
        version = platform.platform()
    return version
def get_dist():
    '''
    Get the current os and version
    '''
    if platform.dist()[0]:
        return platform.dist()[0].lower()
    elif platform.mac_ver()[0]:
        darwin_version = platform.mac_ver()[0].rsplit('.', 1)[0]
        return 'darwin%s' % darwin_version
    elif platform.win32_ver()[0]:
        return platform.win32_ver()[0].lower()
    return 'unknown'
Example #25
0
 def get_sysinfo(self):
     import platform
     (system, node, release, version, machine, processor) = platform.uname()
     sysinfo = {'os.name' : system, 'hostname' : node, 'os.version.number' : version,
                'os.version.string' : release, 'arch' : machine}
     if system == 'Darwin':
         sysinfo['os.name'] = "Mac OS X"
         sysinfo['os.version.number'] = platform.mac_ver()[0]
         sysinfo['os.version.string'] = platform.mac_ver()[0]
     elif (system == 'linux2') or (system in ('sunos5', 'solaris')):
         sysinfo['linux_distrobution'] = platform.linux_distrobution()
         sysinfo['libc_ver'] = platform.libc_ver()        
     return sysinfo
Example #26
0
def check_osx(config):
    if not platform.system() == 'Darwin' or not platform.mac_ver()[0]:
        error('This can only be run on a OS X system!')

    osxver = platform.mac_ver()[0][:platform.mac_ver()[0].rindex('.')]
    osxcfg = config.replace('osx-', 'osx-%s-' % osxver)
    if not osxcfg in OSX_CONFIG:
        error('This target is not supported: %s' % osxcfg)
    if 'carbon' in osxcfg and osxver != '10.6':
        sdk_dir = get_output('xcodebuild', '-sdk', 'macosx10.6', '-version', 'Path')
        if not sdk_dir:
            error('Unable to find OS X 10.6 SDK for the carbon build, aborting.')
        if not os.path.isfile('%s/usr/lib/libstdc++.dylib' % sdk_dir):
            error('Symlink for libstdc++.dylib has not been created, aborting.')
Example #27
0
def sys_id():
    bits = platform.architecture()[0]

    plat = sys.platform

    # Special case: the Snow Leopard builder targets 64-bit.
    if plat == "darwin":
        if platform.mac_ver()[0][:4] == "10.8":
            plat = "macx8"
            bits = "64bit"
        elif platform.mac_ver()[0][:4] == "10.6":
            bits = "64bit"

    return "%s-%s" % (plat, bits)
Example #28
0
File: setup.py Project: PMBio/limix
def mac_workaround(compatible):
    import platform
    from distutils import sysconfig

    conf_vars = sysconfig.get_config_vars()
    if compatible:
        conf_vars['MACOSX_DEPLOYMENT_TARGET'] = '10.9'
        return
    vers = platform.mac_ver()[0].split('.')
    if len(vers) == 3:
        conf_vars['MACOSX_DEPLOYMENT_TARGET'] =\
            vers[0] + '.' + vers[1]
    else:
        conf_vars['MACOSX_DEPLOYMENT_TARGET'] = platform.mac_ver()[0]
Example #29
0
def sessionInfo():
    """ Return a dictionary with session and run information
    """

    version = "%s" % Tools.version

    result = {'name': os.path.basename(sys.argv[0]),
              'timestamp': time.strftime("%a %b %d %X %Y"),
              'version': version,
              'runInfo': [{"key": "commandline", "value": " ".join(sys.argv)}],
              'uname': " / ".join(platform.uname()),
              'dist': " / ".join(platform.dist()),
              'mac_ver': " / ".join([platform.mac_ver()[0], platform.mac_ver()[2]]),
              'python_implementation': platform.python_implementation(),
              'python_version': platform.python_version(),
              'metadata': {
                  "required": {
                      "id": "haplotypes",
                      'version': version,
                      "module": "%s" % os.path.basename(sys.argv[0]),
                      "description": "%s generated this JSON file via command line %s" % (
                          sys.argv[0], " ".join(sys.argv))}},
              'environment': {str(k): str(os.environ[k]) for k in os.environ.keys()}}

    result["python_prefix"] = sys.prefix
    if hasattr(sys, 'real_prefix'):
        result["python_virtualenv"] = True
        result["python_real_prefix"] = sys.real_prefix

    try:
        import psutil
        result["cpus"] = psutil.cpu_count()
        result["logical_cpus"] = psutil.cpu_count(True)
        result["cpu_freq"] = psutil.cpu_freq()
        result["memory"] = dict(psutil.virtual_memory().__dict__)
    except:
        pass

    try:
        import pip
        pip_packages = []
        for i in pip.get_installed_distributions(local_only=True):
            pip_packages.append(str(i))

        result["pip_packages"] = pip_packages
    except:
        pass

    return result
Example #30
0
def macType():
    '''
    If system is a Mac, return the mac type.
    '''
    assert platform.system() in ('Windows', 'Linux', 'Darwin')
    isMac = isSL = amiLion = False
    if platform.system() == 'Darwin':
        isMac = True
        # Script has only been tested on Snow Leopard and Lion.
        assert 6 <= int(platform.mac_ver()[0].split('.')[1]) <= 7
        isSL = isMac and platform.mac_ver()[0].split('.')[1] == '6' \
            and platform.mac_ver()[0].split('.') >= ['10', '6']
        amiLion = isMac and platform.mac_ver()[0].split('.')[1] == '7' \
            and platform.mac_ver()[0].split('.') >= ['10', '7']
    return (isMac, isSL, amiLion)
Example #31
0
if os.name == 'nt':
    WIN32 = True
    from util.apireg import del_connection_info
    try:
        import ctypes
        KERNEL32 = ctypes.windll.LoadLibrary("Kernel32.dll")
    except:
        pass
elif os.name == 'posix':
    ORG_UMASK = os.umask(18)
    os.umask(ORG_UMASK)
    import platform
    if platform.system().lower() == 'darwin':
        DARWIN = True
        # 12 = Sierra, 11 = ElCaptain, 10 = Yosemite, 9 = Mavericks, 8 = MountainLion
        DARWIN_VERSION = int(platform.mac_ver()[0].split('.')[1])
        try:
            import Foundation
            FOUNDATION = True
        except:
            pass

##############################################################################
# SSL CHECKS
##############################################################################
import ssl
HAVE_SSL_CONTEXT = None
try:
    # Test availability of SSLContext (python 2.7.9+)
    ssl.SSLContext
    HAVE_SSL_CONTEXT = True
Example #32
0
extensions = [
    Extension(
        'sstcam_sandbox.d190209_spectra.spe_functions',
        sources=['sstcam_sandbox/d190209_spectra/spe_functions.cc'],
    ),
]


def is_platform_mac():
    return sys.platform == 'darwin'


# Handle mac error: https://github.com/pandas-dev/pandas/issues/23424
if is_platform_mac():
    if 'MACOSX_DEPLOYMENT_TARGET' not in os.environ:
        current_system = LooseVersion(platform.mac_ver()[0])
        python_target = LooseVersion(
            get_config_var('MACOSX_DEPLOYMENT_TARGET'))
        if (python_target <= '10.9') and (current_system >= '10.9'):
            os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.9'
            os.environ['CC'] = 'clang'
            os.environ['CXX'] = 'clang++'

setup(
    name=PACKAGENAME,
    packages=find_packages(),
    version=VERSION,
    description=DESCRIPTION,
    license='BSD3',
    install_requires=[
        'astropy', 'scipy', 'numpy', 'matplotlib', 'tqdm', 'pandas>=0.21.0',
Example #33
0
def is_mac():
    return platform.mac_ver()[0] is not ''
Example #34
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import math
import time
import util
import psutil          # https://code.google.com/p/psutil/wiki/Documentation
import platform


# Determines the operating system in module load time
PYTHON_SYSTEM = platform.system()
OS_IS_OSX = PYTHON_SYSTEM.lower() == 'darwin' and platform.mac_ver()[0]
OS_IS_WIN = PYTHON_SYSTEM.lower() == 'windows'
OS_IS_LINUX = PYTHON_SYSTEM.lower() == 'linux'

OS_NAME = ""
OS_VERSION = ""
osGetCPULoadAvg = None

if OS_IS_LINUX:
    OS_NAME, OS_VERSION, _ = platform.linux_distribution()
    osGetCPULoadAvg = os.getloadavg

elif OS_IS_OSX:
    OS_NAME = "Mac OS X"
    OS_VERSION, _, _ = platform.mac_ver()
    osGetCPULoadAvg = os.getloadavg
Example #35
0
def _current_os_has_gsl_lvl2():
    """ Check whether the current OS should be running GSLv2 """
    return platform.linux_distribution()[0].lower(
    ) == "ubuntu" or platform.mac_ver()[0] != ''
Example #36
0
    if platform == 'ios':
        osx_flags = {
            'extra_link_args': [
                '-framework', 'Foundation', '-framework', 'UIKit',
                '-framework', 'AudioToolbox', '-framework', 'CoreGraphics',
                '-framework', 'QuartzCore', '-framework', 'ImageIO',
                '-framework', 'Accelerate'
            ]
        }
    else:
        osx_flags = {'extra_link_args': ['-framework', 'ApplicationServices']}
    sources['core/image/img_imageio.pyx'] = merge(base_flags, osx_flags)

if c_options['use_avfoundation']:
    import platform as _platform
    mac_ver = [int(x) for x in _platform.mac_ver()[0].split('.')[:2]]
    if mac_ver >= [10, 7]:
        osx_flags = {
            'extra_link_args': ['-framework', 'AVFoundation'],
            'extra_compile_args': ['-ObjC++'],
            'depends': ['core/camera/camera_avfoundation_implem.m']
        }
        sources['core/camera/camera_avfoundation.pyx'] = merge(
            base_flags, osx_flags)
    else:
        print('AVFoundation cannot be used, OSX >= 10.7 is required')

if c_options['use_rpi']:
    sources['lib/vidcore_lite/egl.pyx'] = merge(base_flags, gl_flags)
    sources['lib/vidcore_lite/bcm.pyx'] = merge(base_flags, gl_flags)
Example #37
0
    # #Handling the standard library for C++ on OSX
    #
    # This is mostly related to the compiler version, but since it is much
    # easier to check the OSX version, we are may also use that as an
    # indicator. OSX 10.14 and XCode 10 completely dropped support for
    # libstdc++ which forces is to manipulate the minimum OSX target
    # version when compiling the Cython extensions.
    if sys.platform == 'darwin':
        osx_target = LooseVersion(get_config_var('MACOSX_DEPLOYMENT_TARGET'))
        osx_compiler = LooseVersion('0.0')
        osx_version = LooseVersion('0.0')
        FORCE_TARGET = None
        USE_OSX_VERSION = False
        if USE_OSX_VERSION:
            osx_version = LooseVersion(platform.mac_ver()[0])
            print("OSX build detected, targetting {0} on {1}.".format(
                osx_target, osx_version))
        else:
            import subprocess
            cmd = subprocess.Popen(
                r'gcc --version | grep clang | grep -o -E "(\d+\.)+\d+" | uniq | sort',
                shell=True,
                stdout=subprocess.PIPE)
            for line in cmd.stdout:
                # print(line)
                try:
                    line = line.decode()
                except AttributeError:
                    pass
                line = line.strip()
Example #38
0
log = getLogger(__name__)
stderrlog = getLogger('stderrlog')

# Collect relevant info from OS for reporting purposes (present in User-Agent)
_user_agent = ("conda/{conda_ver} "
               "requests/{requests_ver} "
               "{python}/{py_ver} "
               "{system}/{kernel} {dist}/{ver}")

glibc_ver = gnu_get_libc_version()
if config_platform == 'linux':
    distinfo = platform.linux_distribution()
    dist, ver = distinfo[0], distinfo[1]
elif config_platform == 'osx':
    dist = 'OSX'
    ver = platform.mac_ver()[0]
else:
    dist = platform.system()
    ver = platform.version()

user_agent = _user_agent.format(conda_ver=conda.__version__,
                                requests_ver=requests.__version__,
                                python=platform.python_implementation(),
                                py_ver=platform.python_version(),
                                system=platform.system(),
                                kernel=platform.release(),
                                dist=dist,
                                ver=ver)
if glibc_ver:
    user_agent += " glibc/{}".format(glibc_ver)
Example #39
0
    def onInit(self, showSplash=True, testMode=False):
        """This is launched immediately *after* the app initialises with wx
        :Parameters:

          testMode: bool
        """
        self.SetAppName('PsychoPy3')

        if showSplash:  #showSplash:
            # show splash screen
            splashFile = os.path.join(self.prefs.paths['resources'],
                                      'psychopySplash.png')
            splashImage = wx.Image(name=splashFile)
            splashImage.ConvertAlphaToMask()
            splash = AS.AdvancedSplash(
                None,
                bitmap=splashImage.ConvertToBitmap(),
                timeout=3000,
                agwStyle=AS.AS_TIMEOUT | AS.AS_CENTER_ON_SCREEN,
            )  # transparency?
            w, h = splashImage.GetSize()
            splash.SetTextPosition((int(340), h - 30))
            splash.SetText(
                _translate("Copyright (C) 2020 OpenScienceTools.org"))
        else:
            splash = None

        # SLOW IMPORTS - these need to be imported after splash screen starts
        # but then that they end up being local so keep track in self

        from psychopy.compatibility import checkCompatibility
        # import coder and builder here but only use them later
        from psychopy.app import coder, builder, runner, dialogs

        if '--firstrun' in sys.argv:
            del sys.argv[sys.argv.index('--firstrun')]
            self.firstRun = True
        if 'lastVersion' not in self.prefs.appData:
            # must be before 1.74.00
            last = self.prefs.appData['lastVersion'] = '1.73.04'
            self.firstRun = True
        else:
            last = self.prefs.appData['lastVersion']

        if self.firstRun and not self.testMode:
            pass

        # setup links for URLs
        # on a mac, don't exit when the last frame is deleted, just show menu
        if sys.platform == 'darwin':
            self.menuFrame = MenuFrame(parent=None, app=self)
        # fetch prev files if that's the preference
        if self.prefs.coder['reloadPrevFiles']:
            scripts = self.prefs.appData['coder']['prevFiles']
        else:
            scripts = []
        appKeys = list(self.prefs.appData['builder'].keys())
        if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys):
            exps = self.prefs.appData['builder']['prevFiles']
        else:
            exps = []
        runlist = []

        self.dpi = int(wx.GetDisplaySize()[0] /
                       float(wx.GetDisplaySizeMM()[0]) * 25.4)
        if not (50 < self.dpi < 120):
            self.dpi = 80  # dpi was unreasonable, make one up

        if sys.platform == 'win32':
            # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32
            self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        else:
            self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)

        try:
            self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
        except wx._core.wxAssertionError:
            # if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN
            self._codeFont = wx.Font(self._mainFont.GetPointSize(),
                                     wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL,
                                     wx.FONTWEIGHT_NORMAL)
        # that gets most of the properties of _codeFont but the FaceName
        # FaceName is set in the setting of the theme:
        self.theme = self.prefs.app['theme']

        # removed Aug 2017: on newer versions of wx (at least on mac)
        # this looks too big
        # if hasattr(self._mainFont, 'Larger'):
        #     # Font.Larger is available since wyPython version 2.9.1
        #     # PsychoPy still supports 2.8 (see ensureMinimal above)
        #     self._mainFont = self._mainFont.Larger()
        #     self._codeFont.SetPointSize(
        #         self._mainFont.GetPointSize())  # unify font size

        # create both frame for coder/builder as necess
        if splash:
            splash.SetText(_translate("  Creating frames..."))

        # Parse incoming call
        parser = argparse.ArgumentParser(prog=self)
        parser.add_argument('--builder', dest='builder', action="store_true")
        parser.add_argument('-b', dest='builder', action="store_true")
        parser.add_argument('--coder', dest='coder', action="store_true")
        parser.add_argument('-c', dest='coder', action="store_true")
        parser.add_argument('--runner', dest='runner', action="store_true")
        parser.add_argument('-r', dest='runner', action="store_true")
        view, args = parser.parse_known_args(sys.argv)
        print(args)
        # Check from filetype if any windows need to be open
        if any(arg.endswith('.psyexp') for arg in args):
            view.builder = True
            exps = [file for file in args if file.endswith('.psyexp')]
        if any(arg.endswith('.psyrun') for arg in args):
            view.runner = True
            runlist = [file for file in args if file.endswith('.psyrun')]
        # If still no window specified, use default from prefs
        if not any(
                getattr(view, key) for key in ['builder', 'coder', 'runner']):
            if self.prefs.app['defaultView'] in view:
                setattr(view, self.prefs.app['defaultView'], True)
            elif self.prefs.app['defaultView'] == 'all':
                view.builder = True
                view.coder = True
                view.runner = True

        # Create windows
        if view.runner:
            self.showRunner(fileList=runlist)
        if view.coder:
            self.showCoder(fileList=scripts)
        if view.builder:
            self.showBuilder(fileList=exps)

        # if darwin, check for inaccessible keyboard
        if sys.platform == 'darwin':
            from psychopy.hardware import keyboard
            if keyboard.macPrefsBad:
                title = _translate("Mac keyboard security")
                if platform.mac_ver()[0] < '10.15':
                    settingName = 'Accessibility'
                    setting = 'Privacy_Accessibility'
                else:
                    setting = 'Privacy_ListenEvent'
                    settingName = 'Input Monitoring'
                msg = _translate(
                    "To use high-precision keyboard timing you should "
                    "enable {} for PsychoPy in System Preferences. "
                    "Shall we go there (and you can drag PsychoPy app into "
                    "the box)?").format(settingName)
                dlg = dialogs.MessageDialog(title=title,
                                            message=msg,
                                            type='Query')
                resp = dlg.ShowModal()
                if resp == wx.ID_YES:
                    from AppKit import NSWorkspace
                    from Foundation import NSURL

                    sys_pref_link = ('x-apple.systempreferences:'
                                     'com.apple.preference.security?'
                                     '{}'.format(setting))

                    # create workspace object
                    workspace = NSWorkspace.sharedWorkspace()

                    # Open System Preference
                    workspace.openURL_(NSURL.URLWithString_(sys_pref_link))

        # send anonymous info to www.psychopy.org/usage.php
        # please don't disable this, it's important for PsychoPy's development
        self._latestAvailableVersion = None
        self.updater = None
        self.news = None
        self.tasks = None

        prefsConn = self.prefs.connections

        ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True)
        # tell the user what has changed
        if not ok and not self.firstRun and not self.testMode:
            title = _translate("Compatibility information")
            dlg = dialogs.MessageDialog(parent=None,
                                        message=msg,
                                        type='Info',
                                        title=title)
            dlg.ShowModal()

        if (self.prefs.app['showStartupTips'] and not self.testMode
                and not blockTips):
            tipFile = os.path.join(self.prefs.paths['resources'],
                                   _translate("tips.txt"))
            tipIndex = self.prefs.appData['tipIndex']
            if parse_version(wx.__version__) >= parse_version('4.0.0a1'):
                tp = wx.adv.CreateFileTipProvider(tipFile, tipIndex)
                showTip = wx.adv.ShowTip(None, tp)
            else:
                tp = wx.CreateFileTipProvider(tipFile, tipIndex)
                showTip = wx.ShowTip(None, tp)

            self.prefs.appData['tipIndex'] = tp.GetCurrentTip()
            self.prefs.saveAppData()
            self.prefs.app['showStartupTips'] = showTip
            self.prefs.saveUserPrefs()

        self.Bind(wx.EVT_IDLE, self.onIdle)

        # doing this once subsequently enables the app to open & switch among
        # wx-windows on some platforms (Mac 10.9.4) with wx-3.0:
        v = parse_version
        if sys.platform == 'darwin':
            if v('3.0') <= v(wx.version()) < v('4.0'):
                _Showgui_Hack()  # returns ~immediately, no display
                # focus stays in never-land, so bring back to the app:
                if prefs.app['defaultView'] in [
                        'all', 'builder', 'coder', 'runner'
                ]:
                    self.showBuilder()
                else:
                    self.showCoder()
        # after all windows are created (so errors flushed) create output
        self._appLoaded = True
        if self.coder:
            self.coder.setOutputWindow()  # takes control of sys.stdout

        # flush any errors to the last run log file
        logging.flush()
        sys.stdout.flush()
        # we wanted debug mode while loading but safe to go back to info mode
        if not self.prefs.app['debugMode']:
            logging.console.setLevel(logging.INFO)
        # Runner captures standard streams until program closed
        if self.runner and not self.testMode:
            sys.stdout = self.runner.stdOut
            sys.stderr = self.runner.stdOut

        return True
Example #40
0
        _name = platform.system()
    _METADATA['os'] = SON([
        ('type', platform.system()),
        ('name', _name),
        ('architecture', platform.machine()),
        # Kernel version (e.g. 4.4.0-17-generic).
        ('version', platform.release())
    ])
elif sys.platform == 'darwin':
    _METADATA['os'] = SON([
        ('type', platform.system()),
        ('name', platform.system()),
        ('architecture', platform.machine()),
        # (mac|i|tv)OS(X) version (e.g. 10.11.6) instead of darwin
        # kernel version.
        ('version', platform.mac_ver()[0])
    ])
elif sys.platform == 'win32':
    _METADATA['os'] = SON([
        ('type', platform.system()),
        # "Windows XP", "Windows 7", "Windows 10", etc.
        ('name', ' '.join((platform.system(), platform.release()))),
        ('architecture', platform.machine()),
        # Windows patch level (e.g. 5.1.2600-SP3)
        ('version', '-'.join(platform.win32_ver()[1:3]))
    ])
elif sys.platform.startswith('java'):
    _name, _ver, _arch = platform.java_ver()[-1]
    _METADATA['os'] = SON([
        # Linux, Windows 7, Mac OS X, etc.
        ('type', _name),
Example #41
0
def createLinearRamp(win, rampType=None):
    """Generate the Nx3 values for a linear gamma ramp on the current platform.
    This uses heuristics about known graphics cards to guess the 'rampType' if
    none is exlicitly given.

    Much of this work is ported from LoadIdentityClut.m, written by Mario Kleiner
    for the psychtoolbox

    rampType 0 : an 8-bit CLUT ranging 0:1
        This is seems correct for most windows machines and older OS X systems
        Known to be used by:
            OSX 10.4.9 PPC with GeForceFX-5200

    rampType 1 : an 8-bit CLUT ranging (1/256.0):1
        For some reason a number of macs then had a CLUT that (erroneously?) started with 1/256 rather than 0
        Known to be used by:
            OSX 10.4.9 with ATI Mobility Radeon X1600
            OSX 10.5.8 with ATI Radeon HD-2600
            maybe all ATI cards?

    rampType 2 : a 10-bit CLUT ranging 0:(1023/1024)
        A slightly odd 10-bit CLUT that doesn't quite finish on 1.0!
        Known to be used by:
            OSX 10.5.8 with Geforce-9200M (MacMini)
            OSX 10.5.8 with Geforce-8800

    rampType 3 : a nasty, bug-fixing 10bit CLUT for crumby OS X drivers
        Craziest of them all for Snow leopard. Like rampType 2, except that the upper half of the table has 1/256.0 removed?!!
        Known to be used by:
            OSX 10.6.0 with NVidia Geforce-9200M
    """
    if rampType == None:
        #try to determine rampType from heuristics
        #get sys info
        driver = pyglet.gl.gl_info.get_renderer()
        if sys.platform == 'darwin':
            isOSX = True
            osxVer = platform.mac_ver()[0]
        else:
            isOSX = False
            osxVer = None

        #try to deduce ramp type
        if isOSX:
            if 'NVIDIA' in driver:
                if ("10.5" < osxVer <
                        "10.6"):  #leopard nVidia cards don't finish at 1.0!
                    rampType = 2
                if ("10.6" < osxVer):  #snow leopard cards are plain crazy!
                    rampType = 3
            else:  #is ATI or unkown manufacturer, default to (1:256)/256
                #this is certainly correct for radeon2600 on 10.5.8 and radeonX1600 on 10.4.9
                rampType = 1
        else:  #for win32 and linux this is sensible, not clear about Vista and Windows7
            rampType = 0

    if rampType == 0:
        ramp = numpy.linspace(0.0, 1.0, num=256)
    elif rampType == 1:
        ramp = numpy.linspace(1 / 256.0, 1.0, num=256)
    elif rampType == 2:
        ramp = numpy.linspace(0, 1023.0 / 1024, num=1024)
    elif rampType == 3:
        ramp = numpy.linspace(0, 1023.0 / 1024, num=1024)
        ramp[512:] = ramp[512:] - 1 / 256.0
    logging.info('Using gamma ramp type: %i' % rampType)
    return ramp
Example #42
0
    try:
        set_win32_java_home()
    except:
        traceback.print_exc()

    adb = "platform-tools\\adb.exe"
    sdkmanager = "tools\\bin\\sdkmanager.bat"

    java = maybe_java_home("java.exe")
    javac = maybe_java_home("javac.exe")
    keytool = maybe_java_home("keytool.exe")

    gradlew = "project/gradlew.bat"

elif platform.mac_ver()[0]:
    macintosh = True

    adb = "platform-tools/adb"
    sdkmanager = "tools/bin/sdkmanager"

    java = maybe_java_home("java")
    javac = maybe_java_home("javac")
    keytool = maybe_java_home("keytool")

    os.environ.setdefault("JAVA_HOME", "/usr")

    gradlew = "project/gradlew"

else:
    linux = True
Example #43
0
#!/usr/bin/env python
import os, platform, string, re

arch = platform.machine()

system = platform.system()

#---Determine the OS and version--------------------------------------
if system == 'Darwin':
    osvers = 'mac' + string.join(platform.mac_ver()[0].split('.')[:2], '')
elif system == 'Linux':
    dist = platform.linux_distribution()
    if re.search('SLC', dist[0]):
        osvers = 'slc' + dist[1].split('.')[0]
    elif re.search('CentOS', dist[0]):
        osvers = 'centos' + dist[1].split('.')[0]
    elif re.search('Ubuntu', dist[0]):
        osvers = 'ubuntu' + dist[1].split('.')[0]
    elif re.search('Fedora', dist[0]):
        osvers = 'fedora' + dist[1].split('.')[0]
    else:
        osvers = 'linux' + string.join(
            platform.linux_distribution()[1].split('.')[:2], '')
elif system == 'Windows':
    osvers = win + platform.win32_ver()[0]
else:
    osvers = 'unk-os'

#---Determine the compiler and version--------------------------------
if os.getenv('COMPILER') and os.getenv('COMPILER') not in [
        'native', 'classic'
Example #44
0
    def __init__(self):
        # We don't want sentry making noise if an error is caught when we don't have internet
        sentry_errors = logging.getLogger('sentry.errors')
        sentry_errors.disabled = True

        sentry_uncaught = logging.getLogger('sentry.errors.uncaught')
        sentry_uncaught.disabled = True
        self._sentry_initialized = False

        if SENTRY_SDK_AVAILABLE:
            cacert = None
            if hasattr(sys, "frozen"):
                cacert_resource = get_resource("cacert.pem")
                if cacert_resource is not None and os.path.isfile(
                        cacert_resource):
                    cacert = cacert_resource
                else:
                    log.error(
                        "The SSL certificate bundle file '{}' could not be found"
                        .format(cacert_resource))

            # Don't send log records as events.
            sentry_logging = LoggingIntegration(level=logging.INFO,
                                                event_level=None)

            sentry_sdk.init(dsn=CrashReport.DSN,
                            release=__version__,
                            ca_certs=cacert,
                            default_integrations=False,
                            integrations=[sentry_logging])

            sentry_sdk.init(dsn=CrashReport.DSN,
                            release=__version__,
                            ca_certs=cacert)

            tags = {
                "os:name":
                platform.system(),
                "os:release":
                platform.release(),
                "os:win_32":
                " ".join(platform.win32_ver()),
                "os:mac":
                "{} {}".format(platform.mac_ver()[0],
                               platform.mac_ver()[2]),
                "os:linux":
                " ".join(distro.linux_distribution()),
            }

            self._add_qt_information(tags)

            with sentry_sdk.configure_scope() as scope:
                for key, value in tags.items():
                    scope.set_tag(key, value)

            extra_context = {
                "python:version":
                "{}.{}.{}".format(sys.version_info[0], sys.version_info[1],
                                  sys.version_info[2]),
                "python:bit":
                struct.calcsize("P") * 8,
                "python:encoding":
                sys.getdefaultencoding(),
                "python:frozen":
                "{}".format(hasattr(sys, "frozen"))
            }

            # extra controller and compute information
            from .controller import Controller
            from .compute_manager import ComputeManager
            extra_context["controller:version"] = Controller.instance(
            ).version()
            extra_context["controller:host"] = Controller.instance().host()
            extra_context["controller:connected"] = Controller.instance(
            ).connected()

            for index, compute in enumerate(
                    ComputeManager.instance().computes()):
                extra_context["compute{}:id".format(index)] = compute.id()
                extra_context["compute{}:name".format(index)] = compute.name(),
                extra_context["compute{}:host".format(index)] = compute.host(),
                extra_context["compute{}:connected".format(
                    index)] = compute.connected()
                extra_context["compute{}:platform".format(
                    index)] = compute.capabilities().get("platform")
                extra_context["compute{}:version".format(
                    index)] = compute.capabilities().get("version")

            with sentry_sdk.configure_scope() as scope:
                for key, value in extra_context.items():
                    scope.set_extra(key, value)
Example #45
0
    def capture_exception(self, request=None):
        if not RAVEN_AVAILABLE:
            return
        if os.path.exists(".git"):
            log.warning(
                "A .git directory exist crash report is turn off for developers"
            )
            return
        server_config = Config.instance().get_section_config("Server")
        if server_config.getboolean("report_errors"):
            if self._client is None:
                self._client = raven.Client(CrashReport.DSN,
                                            release=__version__,
                                            raise_send_errors=True,
                                            transport=HTTPTransport)
            if request is not None:
                self._client.http_context({
                    "method": request.method,
                    "url": request.path,
                    "data": request.json,
                })

            context = {
                "os:name":
                platform.system(),
                "os:release":
                platform.release(),
                "os:win_32":
                " ".join(platform.win32_ver()),
                "os:mac":
                "{} {}".format(platform.mac_ver()[0],
                               platform.mac_ver()[2]),
                "os:linux":
                " ".join(distro.linux_distribution()),
                "aiohttp:version":
                aiohttp.__version__,
                "python:version":
                "{}.{}.{}".format(sys.version_info[0], sys.version_info[1],
                                  sys.version_info[2]),
                "python:bit":
                struct.calcsize("P") * 8,
                "python:encoding":
                sys.getdefaultencoding(),
                "python:frozen":
                "{}".format(hasattr(sys, "frozen"))
            }

            if sys.platform.startswith("linux") and not hasattr(sys, "frozen"):
                # add locale information
                try:
                    language, encoding = locale.getlocale()
                    context["locale:language"] = language
                    context["locale:encoding"] = encoding
                except ValueError:
                    pass

                # add GNS3 VM version if it exists
                home = os.path.expanduser("~")
                gns3vm_version = os.path.join(home, ".config", "GNS3",
                                              "gns3vm_version")
                if os.path.isfile(gns3vm_version):
                    try:
                        with open(gns3vm_version) as fd:
                            context["gns3vm:version"] = fd.readline().strip()
                    except OSError:
                        pass

            self._client.tags_context(context)
            try:
                report = self._client.captureException()
            except Exception as e:
                log.error("Can't send crash report to Sentry: {}".format(e))
                return
            log.info("Crash report sent with event ID: {}".format(
                self._client.get_ident(report)))
Example #46
0
    def common_config_args(self):
        # incomplete list is here http://doc.qt.io/qt-5/configure-options.html
        config_args = [
            '-prefix', self.prefix, '-v', '-opensource',
            '-{0}opengl'.format('' if '+opengl' in self.spec else 'no-'),
            '-release', '-shared', '-confirm-license', '-openssl-linked',
            '-optimized-qmake', '-system-freetype',
            '-I{0}/freetype2'.format(self.spec['freetype'].prefix.include),
            '-no-pch'
        ]

        if sys.platform != 'darwin':
            config_args.append('-fontconfig')

        if '@:5.7.1' in self.spec:
            config_args.append('-no-openvg')
        else:
            # FIXME: those could work for other versions
            config_args.extend(
                ['-system-libpng', '-system-libjpeg', '-system-zlib'])

        if '@:5.7.0' in self.spec:
            config_args.extend([
                # NIS is deprecated in more recent glibc,
                # but qt-5.7.1 does not recognize this option
                '-no-nis',
            ])

        if '~examples' in self.spec:
            config_args.extend(['-nomake', 'examples'])

        if '@4' in self.spec and '~phonon' in self.spec:
            config_args.append('-no-phonon')

        if '+dbus' in self.spec:
            dbus = self.spec['dbus'].prefix
            config_args.append('-dbus-linked')
            config_args.append('-I%s/dbus-1.0/include' % dbus.lib)
            config_args.append('-I%s/dbus-1.0' % dbus.include)
            config_args.append('-L%s' % dbus.lib)
        else:
            config_args.append('-no-dbus')

        if '@5:' in self.spec and sys.platform == 'darwin':
            config_args.extend([
                '-no-xinput2',
                '-no-xcb-xlib',
                '-no-pulseaudio',
                '-no-alsa',
            ])

        # FIXME: else: -system-xcb ?

        if '@4' in self.spec and sys.platform == 'darwin':
            config_args.append('-cocoa')

            mac_ver = tuple(platform.mac_ver()[0].split('.')[:2])
            sdkname = 'macosx%s' % '.'.join(mac_ver)
            sdkpath = which('xcrun')('--show-sdk-path',
                                     '--sdk',
                                     sdkname,
                                     output=str)
            config_args.extend([
                '-sdk',
                sdkpath.strip(),
            ])
            use_clang_platform = False
            if self.spec.compiler.name == 'clang' and \
               str(self.spec.compiler.version).endswith('-apple'):
                use_clang_platform = True
            # No one uses gcc-4.2.1 anymore; this is clang.
            if self.spec.compiler.name == 'gcc' and \
               str(self.spec.compiler.version) == '4.2.1':
                use_clang_platform = True
            if use_clang_platform:
                config_args.append('-platform')
                if mac_ver >= (10, 9):
                    config_args.append('unsupported/macx-clang-libc++')
                else:
                    config_args.append('unsupported/macx-clang')

        return config_args
Example #47
0
    def fn(self):
        skip_for_os = _match_decorator_property(
            lldbplatform.translate(oslist), self.getPlatform())
        skip_for_hostos = _match_decorator_property(
            lldbplatform.translate(hostoslist),
            lldbplatformutil.getHostPlatform())
        skip_for_compiler = _match_decorator_property(
            compiler, self.getCompiler()) and self.expectedCompilerVersion(compiler_version)
        skip_for_arch = _match_decorator_property(
            archs, self.getArchitecture())
        skip_for_debug_info = _match_decorator_property(
            debug_info, self.debug_info)
        skip_for_triple = _match_decorator_property(
            triple, lldb.DBG.GetSelectedPlatform().GetTriple())
        skip_for_remote = _match_decorator_property(
            remote, lldb.remote_platform is not None)

        skip_for_swig_version = (
            swig_version is None) or (
            not hasattr(
                lldb,
                'swig_version')) or (
                _check_expected_version(
                    swig_version[0],
                    swig_version[1],
                    lldb.swig_version))
        skip_for_py_version = (
            py_version is None) or _check_expected_version(
            py_version[0], py_version[1], sys.version_info)
        skip_for_macos_version = (macos_version is None) or (
            _check_expected_version(
                macos_version[0],
                macos_version[1],
                platform.mac_ver()[0]))

        # For the test to be skipped, all specified (e.g. not None) parameters must be True.
        # An unspecified parameter means "any", so those are marked skip by default.  And we skip
        # the final test if all conditions are True.
        conditions = [(oslist, skip_for_os, "target o/s"),
                      (hostoslist, skip_for_hostos, "host o/s"),
                      (compiler, skip_for_compiler, "compiler or version"),
                      (archs, skip_for_arch, "architecture"),
                      (debug_info, skip_for_debug_info, "debug info format"),
                      (triple, skip_for_triple, "target triple"),
                      (swig_version, skip_for_swig_version, "swig version"),
                      (py_version, skip_for_py_version, "python version"),
                      (macos_version, skip_for_macos_version, "macOS version"),
                      (remote, skip_for_remote, "platform locality (remote/local)")]
        reasons = []
        final_skip_result = True
        for this_condition in conditions:
            final_skip_result = final_skip_result and this_condition[1]
            if this_condition[0] is not None and this_condition[1]:
                reasons.append(this_condition[2])
        reason_str = None
        if final_skip_result:
            mode_str = {
                DecorateMode.Skip: "skipping",
                DecorateMode.Xfail: "xfailing"}[mode]
            if len(reasons) > 0:
                reason_str = ",".join(reasons)
                reason_str = "{} due to the following parameter(s): {}".format(
                    mode_str, reason_str)
            else:
                reason_str = "{} unconditionally"
            if bugnumber is not None and not six.callable(bugnumber):
                reason_str = reason_str + " [" + str(bugnumber) + "]"
        return reason_str
Example #48
0

use_cuda = check_for_flag("WITH_CUDA", \
                          "Compiling with CUDA support", \
                          "Compiling without CUDA support. To enable CUDA use:")
trace = check_for_flag("TRACE", \
                       "Compiling with trace enabled for Bresenham's Line", \
                       "Compiling without trace enabled for Bresenham's Line")

print()
print("--------------")
print()

# support for compiling in clang
if platform.system().lower() == "darwin":
    os.environ["MACOSX_DEPLOYMENT_TARGET"] = platform.mac_ver()[0]
    os.environ["CC"] = "c++"


def find_in_path(name, path):
    "Find a file in a search path"
    # adapted fom http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/
    for dir in path.split(os.pathsep):
        binpath = pjoin(dir, name)
        if os.path.exists(binpath):
            return os.path.abspath(binpath)
    return None


# export CUDAHOME=/usr/local/cuda
def locate_cuda():
Example #49
0
def macVer():
    """If system is a Mac, return the mac type."""
    assert platform.system() == 'Darwin'
    return [int(x) for x in platform.mac_ver()[0].split('.')]
Example #50
0
import platform

profile = [
    platform.architecture(),
    platform.dist(),
    platform.libc_ver(),
    platform.mac_ver(),
    platform.machine(),
    platform.node(),
    platform.platform(),
    platform.processor(),
    platform.python_build(),
    platform.python_compiler(),
    platform.python_version(),
    platform.system(),
    platform.uname(),
    platform.version(),
]

for item in profile:
    print item
Example #51
0
    def _setSystemInfo(self):
        """system info"""
        # system encoding
        osEncoding = sys.getfilesystemencoding()

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

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

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

        # platform name, etc
        if sys.platform in ['darwin']:
            OSXver, _junk, architecture = platform.mac_ver()
            platInfo = 'darwin ' + OSXver + ' ' + architecture
            # powerSource = ...
        elif sys.platform.startswith('linux'):
            platInfo = 'linux ' + platform.release()
            # powerSource = ...
        elif sys.platform in ['win32']:
            platInfo = 'windowsversion=' + repr(sys.getwindowsversion())
            # powerSource = ...
        else:
            platInfo = ' [?]'
            # powerSource = ...
        self['systemPlatform'] = platInfo
        #self['systemPowerSource'] = powerSource

        # count all unique people (user IDs logged in), and find current user name & UID
        self['systemUser'], self['systemUserID'] = _getUserNameUID()
        try:
            users = shellCall("who -q").splitlines()[0].split()
            self['systemUsersCount'] = len(set(users))
        except:
            self['systemUsersCount'] = False

        # when last rebooted?
        try:
            lastboot = shellCall("who -b").split()
            self['systemRebooted'] = ' '.join(lastboot[2:])
        except:  # windows
            sysInfo = shellCall('systeminfo').splitlines()
            lastboot = [
                line for line in sysInfo if line.startswith("System Up Time")
                or line.startswith("System Boot Time")
            ]
            lastboot += ['[?]']  # put something in the list just in case
            self['systemRebooted'] = lastboot[0].strip()

        # R (and r2py) for stats:
        try:
            Rver = shellCall(["R", "--version"])
            Rversion = Rver.splitlines()[0]
            if Rversion.startswith('R version'):
                self['systemRavailable'] = Rversion.strip()
            try:
                import rpy2
                self['systemRpy2'] = rpy2.__version__
            except ImportError:
                pass
        except:
            pass

        # encryption / security tools:
        try:
            vers, se = shellCall('openssl version', stderr=True)
            if se:
                vers = str(vers) + se.replace('\n', ' ')[:80]
            if vers.strip():
                self['systemSec.OpenSSLVersion'] = vers
        except:
            pass
        try:
            so = shellCall(['gpg', '--version'])
            if so.find('GnuPG') > -1:
                self['systemSec.GPGVersion'] = so.splitlines()[0]
                self['systemSec.GPGHome'] = ''.join([
                    line.replace('Home:', '').lstrip()
                    for line in so.splitlines() if line.startswith('Home:')
                ])
        except:
            pass
        try:
            import ssl
            self['systemSec.pythonSSL'] = True
        except ImportError:
            self['systemSec.pythonSSL'] = False

        # pyo for sound:
        try:
            import pyo
            self['systemPyoVersion'] = '%i.%i.%i' % pyo.getVersion()
            try:
                # requires pyo svn r1024 or higher:
                inp, out = pyo.pa_get_devices_infos()
                for devList in [inp, out]:
                    for key in devList.keys():
                        if isinstance(devList[key]['name'], str):
                            devList[key]['name'] = devList[key]['name'].decode(
                                osEncoding)
                self['systemPyo.InputDevices'] = inp
                self['systemPyo.OutputDevices'] = out
            except AttributeError:
                pass
        except ImportError:
            pass

        # flac (free lossless audio codec) for google-speech:
        flacv = ''
        if sys.platform == 'win32':
            flacexe = 'C:\\Program Files\\FLAC\\flac.exe'
            if os.path.exists(flacexe):
                flacv = core.shellCall(flacexe + ' --version')
        else:
            flac, se = core.shellCall('which flac', stderr=True)
            if not se and flac and not flac.find('Command not found') > -1:
                flacv = core.shellCall('flac --version')
        if flacv:
            self['systemFlacVersion'] = flacv

        # detect internet access or fail quickly:
        #web.setupProxy() & web.testProxy(web.proxies)  # can take a long time to fail if there's no connection
        self['systemHaveInternetAccess'] = web.haveInternetAccess()
        if not self['systemHaveInternetAccess']:
            self['systemHaveInternetAccess'] = 'False (proxies not attempted)'
Example #52
0
import gzip
import json
import platform
import socket
import StringIO
from distutils.version import LooseVersion

from autopkglib import Processor, ProcessorError, URLGetter  # noqa: F401

__all__ = ["GoToMeetingURLProvider"]

HOSTNAME = "builds.cdn.getgo.com"

# workaround for 10.12.x SNI issue
if LooseVersion(platform.mac_ver()[0]) < LooseVersion("10.13.0"):
    HOSTNAME = socket.gethostbyname_ex("builds.cdn.getgo.com")[0]

BASE_URL = "https://" + HOSTNAME + "/g2mupdater/live/config.json"


class GoToMeetingURLProvider(URLGetter):

    """Provides a download URL for the latest GoToMeeting release."""

    input_variables = {
        "base_url": {"required": False, "description": "Default is %s" % BASE_URL}
    }
    output_variables = {
        "url": {"description": "URL to the latest GoToMeeting release."},
        "build": {"description": "Build number of the latest GoToMeeting release."},
def current_os_has_gslv2():
    """ Check whether the current OS is using GSLv2 """
    return platform.linux_distribution()[0].lower() == 'ubuntu' or platform.mac_ver()[0] != ''
def use_old_api():
    return re.match("^(10.7|10.8)(.\d)?$", platform.mac_ver()[0])
Example #55
0
def user_agent():
    """
    Return a string representing the user agent.
    """
    data = {
        "installer": {"name": "pip", "version": pip.__version__},
        "python": platform.python_version(),
        "implementation": {
            "name": platform.python_implementation(),
        },
    }

    if data["implementation"]["name"] == 'CPython':
        data["implementation"]["version"] = platform.python_version()
    elif data["implementation"]["name"] == 'PyPy':
        if sys.pypy_version_info.releaselevel == 'final':
            pypy_version_info = sys.pypy_version_info[:3]
        else:
            pypy_version_info = sys.pypy_version_info
        data["implementation"]["version"] = ".".join(
            [str(x) for x in pypy_version_info]
        )
    elif data["implementation"]["name"] == 'Jython':
        # Complete Guess
        data["implementation"]["version"] = platform.python_version()
    elif data["implementation"]["name"] == 'IronPython':
        # Complete Guess
        data["implementation"]["version"] = platform.python_version()

    if sys.platform.startswith("linux"):
        from pip._vendor import distro
        distro_infos = dict(filter(
            lambda x: x[1],
            zip(["name", "version", "id"], distro.linux_distribution()),
        ))
        libc = dict(filter(
            lambda x: x[1],
            zip(["lib", "version"], libc_ver()),
        ))
        if libc:
            distro_infos["libc"] = libc
        if distro_infos:
            data["distro"] = distro_infos

    if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
        data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}

    if platform.system():
        data.setdefault("system", {})["name"] = platform.system()

    if platform.release():
        data.setdefault("system", {})["release"] = platform.release()

    if platform.machine():
        data["cpu"] = platform.machine()

    if HAS_TLS:
        data["openssl_version"] = ssl.OPENSSL_VERSION

    setuptools_version = get_installed_version("setuptools")
    if setuptools_version is not None:
        data["setuptools_version"] = setuptools_version

    return "{data[installer][name]}/{data[installer][version]} {json}".format(
        data=data,
        json=json.dumps(data, separators=(",", ":"), sort_keys=True),
    )
Example #56
0
 def _os(self):
     release = platform.mac_ver()[0]
     return "osx-%s" % release
Example #57
0
File: utils.py Project: zsvic/nova
def is_osx():
    return platform.mac_ver()[0] != ''
Example #58
0
    def run(self):
        self.compiler = cc.new_compiler(compiler=self.compiler)
        #print(self.compiler.executables)
        if "AR" in os.environ:
            self.compiler.set_executable("archiver", os.environ["AR"])

        if "CC" in os.environ:
            self.compiler.set_executable("compiler", os.environ["CC"])
            self.compiler.set_executable("compiler_so", os.environ["CC"])

        if "LD" in os.environ:
            self.compiler.set_executable("linker_so", os.environ["LD"])

        compiler_preargs = [
            '-std=gnu99',
            '-ffast-math',
            '-DCHIPMUNK_FFI',
            '-g',
            #'-Wno-unknown-pragmas',
            #'-fPIC',
            '-DCP_USE_CGPOINTS=0',
            # '-DCP_ALLOW_PRIVATE_ACCESS']
        ]

        if not self.debug:
            compiler_preargs.append('-DNDEBUG')

        is_android = self.is_android()

        if "CFLAGS" in os.environ:
            cflags = os.environ["CFLAGS"].split()
            for cflag in cflags:
                x = cflag.strip()
                if x != "":
                    compiler_preargs.append(x)
        else:
            if is_android:
                compiler_preargs += ['-DANDROID']

            if platform.system() == 'Darwin':
                #No -O3 on OSX. There's a bug in the clang compiler when using O3.
                mac_ver_float = float('.'.join(
                    platform.mac_ver()[0].split('.')[:2]))
                if mac_ver_float > 10.12:
                    compiler_preargs += ['-arch', 'x86_64']
                else:
                    compiler_preargs += ['-arch', 'i386', '-arch', 'x86_64']

            elif platform.system() == 'Windows':
                compiler_preargs += ['-shared']

                if get_arch() == 32:
                    # We set the stack boundary with -mincoming-stack-boundary=2
                    # from
                    # https://mingwpy.github.io/issues.html#choice-of-msvc-runtime
                    compiler_preargs += [
                        '-O3', '-mincoming-stack-boundary=2', '-m32'
                    ]
                if get_arch() == 64:
                    compiler_preargs += ['-O3', '-m64']

            else:  # Linux, FreeBSD and others
                compiler_preargs += ['-fPIC', '-O3']
                if get_arch() == 64 and not (
                        platform.machine() == 'aarch64'
                        or platform.machine().startswith('arm')):
                    compiler_preargs += ['-m64']
                elif get_arch(
                ) == 32 and not platform.machine().startswith('arm'):
                    compiler_preargs += ['-m32']

        source_folders = [os.path.join('chipmunk_src', 'src')]
        sources = []
        for folder in source_folders:
            for fn in os.listdir(folder):
                fn_path = os.path.join(folder, fn)
                if fn[-1] == 'c':
                    # Ignore cpHastySpace since it depends on pthread which
                    # creates a dependency on libwinpthread-1.dll when built
                    # with  mingw-w64 gcc.
                    # Will prevent the code from being multithreaded, would be
                    # good if some tests could be made to verify the performance
                    # of this.
                    if platform.system(
                    ) != 'Windows' or fn != "cpHastySpace.c":
                        sources.append(fn_path)
                    #sources.append(fn_path)
                elif fn[-1] == 'o':
                    os.remove(fn_path)

        include_dirs = [os.path.join('chipmunk_src', 'include')]

        objs = self.compiler.compile(sources,
                                     include_dirs=include_dirs,
                                     extra_preargs=compiler_preargs)

        linker_preargs = []
        if "LDFLAGS" in os.environ:
            for l in os.environ["LDFLAGS"].split():
                linker_preargs.append(l)
            #linker_preargs.append("-shared")
        else:

            if platform.system() == 'Windows':
                if get_arch() == 32:
                    linker_preargs += ['-m32']
                else:
                    linker_preargs += ['-m64']

            elif platform.system() == 'Darwin':
                self.compiler.set_executable(
                    'linker_so',
                    ['cc', '-dynamiclib', '-arch', 'i386', '-arch', 'x86_64'])

            else:  #Linux, FreeBSD and others
                if platform.machine() == 'x86_64':
                    linker_preargs += ['-fPIC']
                if is_android:
                    linker_preargs += ['-fPIC', '-lm', '-llog']

        if not self.inplace:
            package_dir = os.path.join(self.build_lib, "pymunk")
        else:
            build_py = self.get_finalized_command('build_py')
            package_dir = os.path.abspath(build_py.get_package_dir(".pymunk"))
        self.xoutputs = [os.path.join(package_dir, get_library_name())]
        #package_dir = self.build_lib
        #print("package_dir", package_dir)
        #outpath = os.path.join(package_dir, get_library_name())
        self.compiler.link(cc.CCompiler.SHARED_LIBRARY,
                           objs,
                           get_library_name(),
                           output_dir=package_dir,
                           extra_preargs=linker_preargs)
Example #59
0
from mac_alias import *
from ds_store import *

from . import colors
from . import licensing

try:
    from . import badge
except ImportError:
    badge = None

_hexcolor_re = re.compile(r'#[0-9a-f]{3}(?:[0-9a-f]{3})?')

# The first element in the platform.mac_ver() tuple is a string containing the
# macOS version (e.g., '10.15.6'). Parse into an integer tuple.
MACOS_VERSION = tuple(int(v) for v in platform.mac_ver()[0].split('.'))


class DMGError(Exception):
    def __init__(self, callback, message):
        self.message = message
        callback({'type': 'error::fatal', 'message': message})

    def __str__(self):
        return str(self.message)


def quiet_callback(info):
    pass

Example #60
0
if sys.platform.startswith('linux'):
    sys_platform = 'linux'
elif sys.platform.startswith('freebsd'):
    sys_platform = 'freebsd'
else:
    sys_platform = sys.platform


# Hack to set environment variables before importing distutils
# modules that will fetch them and set the compiler and linker
# to be used. -Saul

if sys_platform == "darwin":
    sipsimple_osx_arch = os.environ.get('SIPSIMPLE_OSX_ARCH', {4: 'i386', 8: 'x86_64'}[ctypes.sizeof(ctypes.c_size_t)])
    sipsimple_osx_sdk = os.environ.get('SIPSIMPLE_OSX_SDK', re.match("(?P<major>\d+.\d+)(?P<minor>.\d+)?", platform.mac_ver()[0]).groupdict()['major'])
    try:
        osx_sdk_path = subprocess.check_output(["xcodebuild", "-version", "-sdk", "macosx%s" % sipsimple_osx_sdk, "Path"]).strip()
    except subprocess.CalledProcessError as e:
        raise RuntimeError("Could not locate SDK path: %s" % str(e))
    arch_flags =  "-arch " + " -arch ".join(sipsimple_osx_arch.split())
    os.environ['CFLAGS'] = os.environ.get('CFLAGS', '') + " %s -mmacosx-version-min=%s -isysroot %s" % (arch_flags, sipsimple_osx_sdk, osx_sdk_path)
    os.environ['LDFLAGS'] = os.environ.get('LDFLAGS', '') + " %s -isysroot %s" % (arch_flags, osx_sdk_path)
    os.environ['ARCHFLAGS'] = arch_flags

from distutils import log
from distutils.dir_util import copy_tree
from distutils.errors import DistutilsError
from Cython.Distutils import build_ext