Python platform.system() Examples

The following are 30 code examples for showing how to use platform.system(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module platform , or try the search function .

Example 1
Project: indras_net   Author: gcallah   File: prop_args.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, model_nm, logfile=None, props=None,
                 loglevel=logging.INFO):
        self.model_nm = model_nm
        self.graph = nx.Graph()
        if props is None:
            self.props = {}
        else:
            self.props = props
            logfile = self.get("log_fname")
        self.logger = Logger(self, model_name=model_nm,logfile=logfile)
        self.graph.add_edge(self, self.logger)
        self["OS"] = platform.system()
        self["model"] = model_nm
        # process command line args and set them as properties:
        prop_nm = None
        for arg in sys.argv:
            # the first arg (-prop) names the property
            if arg.startswith(SWITCH):
                prop_nm = arg.lstrip(SWITCH)
            # the second arg is the property value
            elif prop_nm is not None:
                self[prop_nm] = arg
                prop_nm = None 
Example 2
Project: clikit   Author: sdispater   File: terminal.py    License: MIT License 6 votes vote down vote up
def _init_dimensions(self):
        current_os = platform.system().lower()
        dimensions = None

        if current_os.lower() == "windows":
            dimensions = self._get_terminal_size_windows()
            if dimensions is None:
                dimensions = self._get_terminal_size_tput()
        elif current_os.lower() in ["linux", "darwin"] or current_os.startswith(
            "cygwin"
        ):
            dimensions = self._get_terminal_size_linux()

        if dimensions is None:
            dimensions = 80, 25

        # Ensure we have a valid width
        if dimensions[0] <= 0:
            dimensions = 80, dimensions[1]

        self._width, self._height = dimensions 
Example 3
Project: aegea   Author: kislyuk   File: ssm.py    License: Apache License 2.0 6 votes vote down vote up
def ensure_session_manager_plugin():
    session_manager_dir = os.path.join(config.user_config_dir, "bin")
    PATH = os.environ.get("PATH", "") + ":" + session_manager_dir
    if shutil.which("session-manager-plugin", path=PATH):
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    else:
        os.makedirs(session_manager_dir, exist_ok=True)
        target_path = os.path.join(session_manager_dir, "session-manager-plugin")
        if platform.system() == "Darwin":
            download_session_manager_plugin_macos(target_path=target_path)
        elif platform.linux_distribution()[0] == "Ubuntu":
            download_session_manager_plugin_linux(target_path=target_path)
        else:
            download_session_manager_plugin_linux(target_path=target_path, pkg_format="rpm")
        os.chmod(target_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    return shutil.which("session-manager-plugin", path=PATH) 
Example 4
Project: wechatpy   Author: wechatpy   File: test_session.py    License: MIT License 6 votes vote down vote up
def test_memcached_storage_access_token(self):
        if platform.system() == "Windows":
            return

        from pymemcache.client import Client
        from wechatpy.session.memcachedstorage import MemcachedStorage

        servers = ("127.0.0.1", 11211)
        memcached = Client(servers)
        session = MemcachedStorage(memcached)
        client = WeChatClient(self.app_id, self.secret, session=session)
        with HTTMock(wechat_api_mock):
            token = client.fetch_access_token()
            self.assertEqual("1234567890", token["access_token"])
            self.assertEqual(7200, token["expires_in"])
            self.assertEqual("1234567890", client.access_token) 
Example 5
Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    License: Apache License 2.0 6 votes vote down vote up
def build_user_agent():
	"""Build a Mozilla/5.0 compatible User-Agent string"""

	global USER_AGENT
	if USER_AGENT:
		return USER_AGENT

	ua_tuple = (
		'Mozilla/5.0',
		'(%s; U; %s; en-us)' % (platform.system(), platform.architecture()[0]),
		'Python/%s' % platform.python_version(),
		'(KHTML, like Gecko)',
		'speedtest-cli/%s' % __version__
	)
	USER_AGENT = ' '.join(ua_tuple)
	printer(USER_AGENT, debug=True)
	return USER_AGENT 
Example 6
Project: ciocheck   Author: ContinuumIO   File: formatters.py    License: MIT License 6 votes vote down vote up
def format_string(cls, old_contents):
        """Format file for use with task queue."""
        # cmd_root is assigned to formatter inside format_task... ugly!
        style_config = os.path.join(cls.cmd_root, cls.config_file)
        # It might be tempting to use the "inplace" option to FormatFile, but
        # it doesn't do an atomic replace, which is dangerous, so don't use
        # it unless you submit a fix to yapf.
        (new_contents, changed) = FormatCode(
            old_contents, style_config=style_config)

        if platform.system() == 'Windows':
            # yapf screws up line endings on windows
            new_contents = new_contents.replace("\r\n", "\n")

            if len(old_contents) == 0:
                # Windows yapf seems to force a newline? I dunno
                new_contents = ""
        return old_contents, new_contents, 'utf-8' 
Example 7
Project: multibootusb   Author: mbusb   File: syslinux.py    License: GNU General Public License v2.0 6 votes vote down vote up
def gpt_part_table(usb_disk):
    """
    Check if selected USB contain GPT or MBR partition table
    :return: True if GPT else False
    """
    if platform.system() == "Linux":
        _cmd_out = subprocess.check_output("parted  " + usb_disk[:-1] + " print", shell=True)
        if b'msdos' in _cmd_out:
            return False
        elif b'gpt' in _cmd_out:
            return True
    elif platform.system() == 'Windows':
        if config.usb_gpt is True:
            return True
        elif config.usb_gpt is False:
            return False 
Example 8
Project: multibootusb   Author: mbusb   File: usb.py    License: GNU General Public License v2.0 6 votes vote down vote up
def is_block(usb_disk):
    """
    Function to detect if the USB is block device
    :param usb_disk: USB disk path
    :return: True is devie is block device else False
    """
    import stat
    if platform.system() == 'Linux':
        if len(usb_disk) != 9:
            return False
    elif platform.system() == 'Windows':
        if len(usb_disk) != 2:
            return False
        else:
            return True
    try:
        mode = os.stat(usb_disk).st_mode
        gen.log(mode)
        gen.log(stat.S_ISBLK(mode))
    except:
        return False

    return stat.S_ISBLK(mode) 
Example 9
Project: multibootusb   Author: mbusb   File: install.py    License: GNU General Public License v2.0 6 votes vote down vote up
def copy_iso(src, dst):
    """
    A simple wrapper for copying larger files. This is necessary as
    shutil copy files is much slower under Windows platform
    :param src: Path to source file
    :param dst: Destination directory
    :return:
    """
    if platform.system() == "Windows":
        # Note that xcopy asks if the target is a file or a directory when
        # source filename (or dest filename) contains space(s) and the target
        # does not exist.
        assert os.path.exists(dst)
        subprocess.call(['xcopy', '/Y', src, dst], shell=True)
    elif platform.system() == "Linux":
        shutil.copy(src, dst) 
Example 10
Project: multibootusb   Author: mbusb   File: qemu.py    License: GNU General Public License v2.0 6 votes vote down vote up
def find_qemu():
        """
        Check if QEMU is available on host system and return path of the binary
        :return: path to QEMU program or None otherwise.
        """
        if platform.system() == "Linux":
            if subprocess.call('which qemu-system-x86_64', shell=True) == 0:
                qemu = "qemu-system-x86_64"
            elif subprocess.call('which qemu', shell=True) == 0:
                qemu = "qemu"
            else:
                qemu = ""

        elif platform.system() == "Windows":
            qemu = find_qemu_exe()

        if qemu:
            log("QEMU: using " + qemu)
        else:
            log("QEMU: ERROR: not found!")

        return qemu 
Example 11
Project: multibootusb   Author: mbusb   File: persistence.py    License: GNU General Public License v2.0 6 votes vote down vote up
def detect_missing_tools(distro):
    tools_dir = os.path.join('data', 'tools')
    if platform.system() == 'Windows':
        _7zip_exe = gen.resource_path(
            os.path.join(tools_dir, '7zip', '7z.exe'))
        e2fsck_exe = gen.resource_path(os.path.join(tools_dir, 'cygwin', 'e2fsck.exe'))
        resize2fs_exe = gen.resource_path(os.path.join(tools_dir, 'cygwin', 'resize2fs.exe'))
    else:
        _7zip_exe = '7z'
        e2fsck_exe = 'e2fsck'
        resize2fs_exe = 'resize2fs'
    if distro not in creator_dict or \
       creator_dict[distro][0] is not create_persistence_using_resize2fs:
        return None
    try:
        with open(os.devnull) as devnull:
            for tool in [e2fsck_exe, resize2fs_exe]:
                p = subprocess.Popen([tool], stdout=devnull, stderr=devnull)
                p.communicate()
    except FileNotFoundError:  # Windows
        return "'%s.exe' is not installed or not available for use." % tool
    except OSError:            # Linux
        return "'%s' is not installed or not available for use." % tool
    return None 
Example 12
Project: multibootusb   Author: mbusb   File: admin.py    License: GNU General Public License v2.0 6 votes vote down vote up
def isUserAdmin():
    """
    @return: True if the current user is an 'Admin' whatever that means
    (root on Unix), otherwise False.

    Warning: The inner function fails unless you have Windows XP SP2 or
    higher. The failure causes a traceback to be gen.loged and this
    function to return False.
    """

    if platform.system() == "Windows":
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            gen.log("Admin check failed, assuming not an admin.")
            return False
    elif platform.system() == "Linux":
        return os.getuid() == 0
    else:
        raise RuntimeError("Unsupported operating system for this module: %s" % (os.name,)) 
Example 13
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: diagnose.py    License: Apache License 2.0 6 votes vote down vote up
def parse_args():
    """Parse arguments."""
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description='Diagnose script for checking the current system.')
    choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
    for choice in choices:
        parser.add_argument('--' + choice, default=1, type=int,
                            help='Diagnose {}.'.format(choice))
    parser.add_argument('--region', default='', type=str,
                        help="Additional sites in which region(s) to test. \
                        Specify 'cn' for example to test mirror sites in China.")
    parser.add_argument('--timeout', default=10, type=int,
                        help="Connection test timeout threshold, 0 to disable.")
    args = parser.parse_args()
    return args 
Example 14
Project: XFLTReaT   Author: earthquake   File: common.py    License: MIT License 6 votes vote down vote up
def get_os_type():
	os_type = platform.system()
	if os_type == "Linux":
		return OS_LINUX

	if os_type == "Darwin":
		return OS_MACOSX

	if os_type == "Windows":
		return OS_WINDOWS

	if os_type == "FreeBSD":
		return OS_FREEBSD

	if os_type == "OpenBSD":
		return OS_OPENBSD

	return OS_UNKNOWN

# get the release of the OS 
Example 15
Project: lichess-bot   Author: ShailChoksi   File: ColorLogger.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def enable_color_logging(debug_lvl=logging.DEBUG):
    if platform.system() == 'Windows':
        # Windows does not support ANSI escapes and we are using API calls to set the console color
        logging.StreamHandler.emit = add_coloring_to_emit_windows(logging.StreamHandler.emit)
    else:
        # all non-Windows platforms are supporting ANSI escapes so we use them
        logging.StreamHandler.emit = add_coloring_to_emit_ansi(logging.StreamHandler.emit)

    root = logging.getLogger()
    root.setLevel(debug_lvl)

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(debug_lvl)

    # FORMAT from https://github.com/xolox/python-coloredlogs
    FORMAT = '%(asctime)s %(name)s[%(process)d] \033[1m%(levelname)s\033[0m %(message)s'
    formatter = logging.Formatter(FORMAT, "%Y-%m-%d %H:%M:%S")

    ch.setFormatter(formatter) 
Example 16
Project: alibuild   Author: alisw   File: utilities.py    License: GNU General Public License v3.0 6 votes vote down vote up
def detectArch():
  try:
    with open("/etc/os-release") as osr:
      osReleaseLines = osr.readlines()
    hasOsRelease = True
  except (IOError,OSError):
    osReleaseLines = []
    hasOsRelease = False
  try:
    import platform
    if platform.system() == "Darwin":
      return "osx_x86-64"
  except:
    pass
  try:
    import platform, distro
    platformTuple = distro.linux_distribution()
    platformSystem = platform.system()
    platformProcessor = platform.processor()
    if " " in platformProcessor:
      platformProcessor = platform.machine()
    return doDetectArch(hasOsRelease, osReleaseLines, platformTuple, platformSystem, platformProcessor)
  except:
    return doDetectArch(hasOsRelease, osReleaseLines, ["unknown", "", ""], "", "") 
Example 17
Project: pyhanlp   Author: hankcs   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def write_config(root=None):
    if root and os.name == 'nt':
        root = root.replace('\\', '/')  # For Windows
    if root and platform.system().startswith('CYGWIN'):  # For cygwin
        if root.startswith('/usr/lib'):
            cygwin_root = os.popen('cygpath -w /').read().strip().replace('\\', '/')
            root = cygwin_root + root[len('/usr'):]
        elif STATIC_ROOT.startswith('/cygdrive'):
            driver = STATIC_ROOT.split('/')
            cygwin_driver = '/'.join(driver[:3])
            win_driver = driver[2].upper() + ':'
            root = root.replace(cygwin_driver, win_driver)
    content = []
    with open_(PATH_CONFIG, encoding='utf-8') as f:
        for line in f:
            if root:
                if line.startswith('root'):
                    line = 'root={}{}'.format(root, os.linesep)
            content.append(line)
    with open_(PATH_CONFIG, 'w', encoding='utf-8') as f:
        f.writelines(content) 
Example 18
Project: pyspectator   Author: it-geeks-club   File: processor.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __get_processor_name(cls):
        cpu_name = None
        os_name = platform.system()
        if os_name == 'Windows':
            cpu_name = platform.processor()
        elif os_name == 'Darwin':
            os.environ['PATH'] = os.environ['PATH'] + os.pathsep + '/usr/sbin'
            command = ('sysctl', '-n', 'machdep.cpu.brand_string')
            output = subprocess.check_output(command)
            if output:
                cpu_name = output.decode().strip()
        elif os_name == 'Linux':
            all_info = subprocess.check_output('cat /proc/cpuinfo', shell=True)
            all_info = all_info.strip().split(os.linesep.encode())
            for line in all_info:
                line = line.decode()
                if 'model name' not in line:
                    continue
                cpu_name = re.sub('.*model name.*:', str(), line, 1).strip()
                break
        return cpu_name 
Example 19
Project: Andromeda   Author: liucaide   File: cd_tools.py    License: MIT License 6 votes vote down vote up
def cd_sys_type():
    """
    :return: 平台类型 0 win, 1 mac  2 Linux 3 其他
    """
    """
    a = sys.platform
    if a == 'win32' or a == 'win64':
        return 0
    elif a == 'darwin':
        return 1
    else:
        return 2
    """
    a = platform.system()
    if a == 'Windows':
        return 0
    elif a == 'Darwin':
        return 1
    elif a == 'Linux':
        return 2
    else:
        return 3 
Example 20
Project: indras_net   Author: gcallah   File: prop_args2.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, model_nm, logfile=None, prop_dict=None,
                 loglevel=logging.INFO):
        """
        Loads and sets properties in the following order:
        1. The Database
        2. The User's Environment (operating system, dev/prod settings, etc.)
        3. Property File
        4. Command Line
        5. Questions Prompts During Run-Time
        """
        self.logfile = logfile
        self.model_nm = model_nm
        self.graph = nx.Graph()
        self.props = {}

        # 1. The Database
        self.set_props_from_db()

        # 2. The Environment
        self.overwrite_props_from_env()

        # 3. Property File
        self.overwrite_props_from_dict(prop_dict)

        if self.props[UTYPE].val in (TERMINAL, IPYTHON, IPYTHON_NB):
            # 4. process command line args and set them as properties:
            self.overwrite_props_from_cl()

            # 5. Ask the user questions.
            self.overwrite_props_from_user()

        elif self.props[UTYPE].val == WEB:
            self.props[PERIODS] = Prop(val=1)
            self.props[BASE_DIR] = Prop(val=os.environ[BASE_DIR])

        self.logger = Logger(self, model_name=model_nm, logfile=logfile)
        self.graph.add_edge(self, self.logger) 
Example 21
Project: indras_net   Author: gcallah   File: prop_args2.py    License: GNU General Public License v3.0 5 votes vote down vote up
def overwrite_props_from_env(self):
        global user_type
        user_type = get_prop_from_env()
        self.props[UTYPE] = Prop(val=user_type)
        self.props[OS] = Prop(val=platform.system()) 
Example 22
Project: cyberdisc-bot   Author: CyberDiscovery   File: bot.py    License: MIT License 5 votes vote down vote up
def register_metadata(ctx):
    """Attach additional data to sentry events."""
    with configure_scope() as scope:
        scope.user = {"id": ctx.author.id, "username": str(ctx.author)}
        scope.set_context("client_os", {"name": system(), "version": release()})
        scope.set_tag("command", ctx.message.content)
        scope.set_tag("channel", str(ctx.channel)) 
Example 23
Project: arm_now   Author: nongiach   File: utils.py    License: MIT License 5 votes vote down vote up
def distribution():
    system = platform.system().lower()
    if system != 'darwin':
        return platform.linux_distribution()[0].lower()
    return system 
Example 24
Project: ALF   Author: blackberry   File: _qemu.py    License: Apache License 2.0 5 votes vote down vote up
def _kill_qemu(self):
        if platform.system() == "Windows":
            with open(os.devnull, "w") as fp:
                subprocess.call(["taskkill", "/IM", os.path.basename(self.QEMU_BIN), "/f"],
                                stdout=fp, stderr=fp) 
Example 25
Project: wechatpy   Author: wechatpy   File: test_session.py    License: MIT License 5 votes vote down vote up
def test_memcached_storage_init(self):
        if platform.system() == "Windows":
            return

        from pymemcache.client import Client
        from wechatpy.session.memcachedstorage import MemcachedStorage

        servers = ("127.0.0.1", 11211)
        memcached = Client(servers)
        session = MemcachedStorage(memcached)
        client = WeChatClient(self.app_id, self.secret, session=session)
        self.assertTrue(isinstance(client.session, MemcachedStorage)) 
Example 26
Project: cherrypy   Author: cherrypy   File: test_static.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_unicode_filesystem(tmpdir):
    filename = tmpdir / ntou('☃', 'utf-8')
    tmpl = 'File system encoding ({encoding}) cannot support unicode filenames'
    msg = tmpl.format(encoding=sys.getfilesystemencoding())
    try:
        io.open(str(filename), 'w').close()
    except UnicodeEncodeError:
        pytest.skip(msg) 
Example 27
Project: cherrypy   Author: cherrypy   File: test_refleaks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_threadlocal_garbage(self):
        if platform.system() == 'Darwin':
            self.skip('queue issues; see #1474')
        success = itertools.count()

        def getpage():
            host = '%s:%s' % (self.interface(), self.PORT)
            if self.scheme == 'https':
                c = HTTPSConnection(host)
            else:
                c = HTTPConnection(host)
            try:
                c.putrequest('GET', '/')
                c.endheaders()
                response = c.getresponse()
                body = response.read()
                self.assertEqual(response.status, 200)
                self.assertEqual(body, b'Hello world!')
            finally:
                c.close()
            next(success)

        ITERATIONS = 25

        ts = [
            threading.Thread(target=getpage)
            for _ in range(ITERATIONS)
        ]

        for t in ts:
            t.start()

        for t in ts:
            t.join()

        self.assertEqual(next(success), ITERATIONS) 
Example 28
Project: LPHK   Author: nimaid   File: files.py    License: GNU General Public License v3.0 5 votes vote down vote up
def open_file_folder(path):
    try:
        if platform.system() == "Windows":
            os.startfile(path)
        elif platform.system() == "Darwin":
            subprocess.Popen(["open", path])
        else:
            subprocess.Popen(["xdg-open", path])
    except:
        print("[files] Could not open file or folder " + path) 
Example 29
Project: multibootusb   Author: mbusb   File: osdriver.py    License: GNU General Public License v2.0 5 votes vote down vote up
def wmi_get_drive_info(usb_disk):
    assert platform.system() == 'Windows'
    for partition in wmi.WMI().Win32_DiskPartition():
        logical_disks = partition.associators("Win32_LogicalDiskToPartition")
        # Here, 'disk' is a windows logical drive rather than a physical drive
        for disk in logical_disks:
            if disk.Caption == usb_disk:
                return (partition, disk)
    raise RuntimeError('Failed to obtain drive information ' + usb_disk) 
Example 30
Project: multibootusb   Author: mbusb   File: osdriver.py    License: GNU General Public License v2.0 5 votes vote down vote up
def initialize():
    logging.root.setLevel(logging.DEBUG)
    fmt = '%(asctime)s.%(msecs)03d %(name)s %(levelname)s %(message)s'
    datefmt = '%H:%M:%S'
    the_handler = logging.handlers.RotatingFileHandler(
        osdriver.mbusb_log_file(), 'a', 1024*1024, 5)
    the_handler.setFormatter(logging.Formatter(fmt, datefmt))
    logging.root.addHandler(the_handler)

    if platform.system() == 'Windows':
        import pythoncom
        pythoncom.CoInitialize()