Python platform.system() Examples

The following are 30 code examples of platform.system(). 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 also want to check out all available functions/classes of the module platform , or try the search function .
Example #1
Source File: ssm.py    From aegea with Apache License 2.0 9 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 #2
Source File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    From L.E.S.M.A with Apache License 2.0 8 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 #3
Source File: install.py    From multibootusb with GNU General Public License v2.0 7 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 #4
Source File: qemu.py    From multibootusb with 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 #5
Source File: ColorLogger.py    From lichess-bot with 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 #6
Source File: common.py    From XFLTReaT with 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 #7
Source File: diagnose.py    From dynamic-training-with-apache-mxnet-on-aws with 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 #8
Source File: utilities.py    From alibuild with 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 #9
Source File: __init__.py    From pyhanlp with 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 #10
Source File: syslinux.py    From multibootusb with 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 #11
Source File: processor.py    From pyspectator with 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 #12
Source File: formatters.py    From ciocheck with 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 #13
Source File: persistence.py    From multibootusb with 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 #14
Source File: test_session.py    From wechatpy with 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 #15
Source File: usb.py    From multibootusb with 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 #16
Source File: cd_tools.py    From Andromeda with 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 #17
Source File: terminal.py    From clikit with 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 #18
Source File: computer.py    From pyspectator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __get_os_name(cls):
        system = '{} {}'.format(platform.system(), platform.release()).strip()
        if ('Linux' in system) and ('' not in platform.linux_distribution()):
            system = ' '.join(platform.linux_distribution())
        return system 
Example #19
Source File: admin.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def adminCmd(cmd, fork=False, gui=False):
    """
    This simple function checks for a sudo command and runs a command using it.
    This function tries to launch given script with root access using pkexec/gksu/gksudo/kdesu/kdesudo,
    if one of them is already installed.
    PyQt4 is used as GUI.
    Author : sundar
    """
    sudo_cmd = ''
    if os.getuid() == 0:
        sudo_cmd = cmd
    else:
        if os.system('which pkexec') == 0:
            if gui:
                # By default, pkexec disallows X11 apps. Restore DISPLAY & XAUTHORITY
                # to allow it. man 1 pkexec/"SECURITY NOTES" section
                cmd = ['export DISPLAY=$DISPLAY; export XAUTHORITY=$XAUTHORITY; '] + cmd
            sudo_cmd = ['pkexec', '/bin/sh', '-c']
        elif os.system('which gksudo') == 0:
            sudo_cmd = ["gksudo", "--", "/bin/sh", "-c"]
        elif os.system('which gksu') == 0:
            sudo_cmd = ["gksu"]
        elif os.system('which kdesudo') == 0:
            sudo_cmd = ["kdesudo", "-t", "-c"]    # http://www.unix.com/man-page/debian/1/kdesudo/
        elif os.system('which kdesu') == 0:
            sudo_cmd = ["kdesu", "-t", "-c"]      # http://linux.die.net/man/1/kdesu
        else:
            QtWidgets.QMessageBox.information('No root...',
                                          'Could not find any of: pkexec, sudo, gksu, kdesu, gksudo, or kdesudo.\n'
                                          'Please install one then restart multibootusb.')
            sys.exit(0)
    final_cmd = ' '.join(sudo_cmd + ['"' + ' '.join(cmd).replace('"', '\\"') + '"'])
    gen.log("Executing ==>  " + final_cmd)
    if fork:
        return subprocess.Popen(final_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, shell=True)
    else:
        ret = subprocess.call(final_cmd, shell=True)
        gen.log("Process returned ==>   " + str(ret))
        return ret 
Example #20
Source File: utils.py    From script.module.inputstreamhelper with MIT License 5 votes vote down vote up
def arch():
    """Map together, cache and return the system architecture"""

    if hasattr(arch, 'cached'):
        return getattr(arch, 'cached')

    from platform import architecture, machine
    sys_arch = machine()
    if sys_arch == 'AMD64':
        sys_arch_bit = architecture()[0]
        if sys_arch_bit == '32bit':
            sys_arch = 'x86'  # else, sys_arch = AMD64

    elif 'armv' in sys_arch:
        import re
        arm_version = re.search(r'\d+', sys_arch.split('v')[1])
        if arm_version:
            sys_arch = 'armv' + arm_version.group()

    if sys_arch in config.ARCH_MAP:
        sys_arch = config.ARCH_MAP[sys_arch]

    log(0, 'Found system architecture {arch}', arch=sys_arch)

    arch.cached = sys_arch
    return sys_arch 
Example #21
Source File: utils.py    From script.module.inputstreamhelper with MIT License 5 votes vote down vote up
def cmd_exists(cmd):
    """Check whether cmd exists on system."""
    # https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
    import subprocess
    return subprocess.call(['type ' + cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0 
Example #22
Source File: utils.py    From script.module.inputstreamhelper with MIT License 5 votes vote down vote up
def system_os():
    """Get system platform, and remember this information"""

    if hasattr(system_os, 'cached'):
        return getattr(system_os, 'cached')

    from xbmc import getCondVisibility
    if getCondVisibility('system.platform.android'):
        sys_name = 'Android'
    else:
        from platform import system
        sys_name = system()

    system_os.cached = sys_name
    return sys_name 
Example #23
Source File: discordclient.py    From SpaceXLaunchBot with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        logging.info("Client initialised")

        self.ds = storage.DataStore(config.PICKLE_DUMP_LOCATION)
        logging.info("Data storage initialised")

        if platform.system() == "Linux":
            self.loop.add_signal_handler(
                signal.SIGTERM, lambda: self.loop.create_task(self.shutdown())
            )
            logging.info("Signal handler for SIGTERM registered")

        self.loop.create_task(notifications.notification_task(self))
        discordhealthcheck.start(self) 
Example #24
Source File: toolkit.py    From PickTrue with MIT License 5 votes vote down vote up
def open_sys_explorer(path):
    ptf = platform.system().lower()
    path = Path(path)
    if "darwin" in ptf:
        return os.system('open %s' % path)
    elif 'windows' in ptf:
        return os.system('explorer.exe "%s"' % path)
    elif 'linux' in ptf:
        return os.system('xdg-open %s' % path)
    return info('平台不支持') 
Example #25
Source File: diagnose.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def check_os():
    print('----------System Info----------')
    print('Platform     :', platform.platform())
    print('system       :', platform.system())
    print('node         :', platform.node())
    print('release      :', platform.release())
    print('version      :', platform.version()) 
Example #26
Source File: qemu.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def find_qemu_exe():
    exe_name = 'qemu-system-x86_64.exe'
    if hasattr(config, 'qemu_exe_path'):
        return config.qemu_exe_path
    if not getattr(config, 'qemu_use_builtin', True):
        for wellknown_path in [
                r'c:\Program Files\qemu',
                r'd:\Program Files\qemu',
                r'e:\Program Files\qemu',
                ]:
            exe_path = os.path.join(wellknown_path, exe_name)
            if os.path.exists(exe_path):
                return exe_path
    return resource_path(os.path.join("data", "tools", "qemu", exe_name)) 
Example #27
Source File: persistence.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def create_persistence_using_mkfs(persistence_fname, persistence_size):
    persistence_path = os.path.join(config.usb_mount, 'multibootusb',
                                    iso.iso_basename(config.image_path),
                                    persistence_fname)
    volume_name = os.path.basename(persistence_fname)
    if platform.system() == 'Windows':
        tools_dir = os.path.join('data', 'tools')
        mke2fs_relative_path = os.path.join(tools_dir, 'mkfs', 'mke2fs.exe')
        mkfs = gen.resource_path(mke2fs_relative_path)
        dd_relative_path = os.path.join(tools_dir, 'dd', 'dd.exe')
        dd = gen.resource_path(dd_relative_path)
        persistence_mkfs_cmd = 'echo y|' + mkfs + ' -b 1024 ' + \
                               '-L ' + volume_name + ' ' + \
                               persistence_path
    else:
        mkfs = 'mkfs.ext3'
        dd = 'dd'
        persistence_mkfs_cmd = mkfs + ' -F ' + persistence_path

    mbytes =  persistence_size / 1024 / 1024
    persistence_dd_cmd = dd + ' if=/dev/zero ' + \
                         'of=' + persistence_path + \
                         ' bs=1M count=' + str(int(mbytes))

    gen.log('Executing ==>' + persistence_dd_cmd)
    config.status_text = 'Creating persistence file...'

    if subprocess.call(persistence_dd_cmd, shell=True) == 0:
        gen.log("\nSuccessfully created persistence file...\n")

    if config.distro != 'fedora':
        gen.log('Applying filesystem to persistence file...')
        config.status_text = 'Applying filesystem to persistence file. Please wait...'
        gen.log('Executing ==> ' + persistence_mkfs_cmd)
        config.status_text = 'Applying filesystem to persistence file...'
        if subprocess.call(persistence_mkfs_cmd, shell=True) == 0:
            gen.log("\nSuccessfully applied filesystem...\n") 
Example #28
Source File: test_base.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def test_data_dir(self,):
        prev_data_dir = data_dir()
        system = platform.system()
        if system != 'Windows':
            self.assertEqual(data_dir(), op.join(op.expanduser('~'), '.mxnet'))
        os.environ['MXNET_HOME'] = '/tmp/mxnet_data'
        self.assertEqual(data_dir(), '/tmp/mxnet_data')
        del os.environ['MXNET_HOME']
        self.assertEqual(data_dir(), prev_data_dir) 
Example #29
Source File: base.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def data_dir_default():
    """

    :return: default data directory depending on the platform and environment variables
    """
    system = platform.system()
    if system == 'Windows':
        return os.path.join(os.environ.get('APPDATA'), 'mxnet')
    else:
        return os.path.join(os.path.expanduser("~"), '.mxnet') 
Example #30
Source File: admin.py    From multibootusb with GNU General Public License v2.0 5 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,))