Python platform.uname() Examples

The following are 30 code examples of platform.uname(). 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: _workflow.py    From oggm with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_sys_info():
    """Returns system information as a dict"""

    blob = []
    try:
        (sysname, nodename, release,
         version, machine, processor) = platform.uname()
        blob.extend([
            ("python", "%d.%d.%d.%s.%s" % sys.version_info[:]),
            ("python-bits", struct.calcsize("P") * 8),
            ("OS", "%s" % (sysname)),
            ("OS-release", "%s" % (release)),
            ("machine", "%s" % (machine)),
            ("processor", "%s" % (processor)),
        ])
    except BaseException:
        pass

    return blob 
Example #2
Source File: test_windows.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_special_pid(self):
        p = psutil.Process(4)
        self.assertEqual(p.name(), 'System')
        # use __str__ to access all common Process properties to check
        # that nothing strange happens
        str(p)
        p.username()
        self.assertTrue(p.create_time() >= 0.0)
        try:
            rss, vms = p.memory_info()[:2]
        except psutil.AccessDenied:
            # expected on Windows Vista and Windows 7
            if not platform.uname()[1] in ('vista', 'win-7', 'win7'):
                raise
        else:
            self.assertTrue(rss > 0) 
Example #3
Source File: rmEngine.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def writeRiskLog(self, content):
        """快速发出日志事件"""
        # 发出报警提示音

        if platform.uname() == 'Windows':
            import winsound
            winsound.PlaySound("SystemHand", winsound.SND_ASYNC) 
        
        # 发出日志事件
        log = VtLogData()
        log.logContent = content
        log.gatewayName = self.name
        event = Event(type_=EVENT_LOG)
        event.dict_['data'] = log
        self.eventEngine.put(event)      
    
    # ---------------------------------------------------------------------- 
Example #4
Source File: __main__.py    From discord.py with MIT License 6 votes vote down vote up
def show_version():
    entries = []

    entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info))
    version_info = discord.version_info
    entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info))
    if version_info.releaselevel != 'final':
        pkg = pkg_resources.get_distribution('discord.py')
        if pkg:
            entries.append('    - discord.py pkg_resources: v{0}'.format(pkg.version))

    entries.append('- aiohttp v{0.__version__}'.format(aiohttp))
    entries.append('- websockets v{0.__version__}'.format(websockets))
    uname = platform.uname()
    entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname))
    print('\n'.join(entries)) 
Example #5
Source File: test_platform.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_uname_win32_ARCHITEW6432(self):
        # Issue 7860: make sure we get architecture from the correct variable
        # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
        # using it, per
        # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
        try:
            with test_support.EnvironmentVarGuard() as environ:
                if 'PROCESSOR_ARCHITEW6432' in environ:
                    del environ['PROCESSOR_ARCHITEW6432']
                environ['PROCESSOR_ARCHITECTURE'] = 'foo'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'foo')
                environ['PROCESSOR_ARCHITEW6432'] = 'bar'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'bar')
        finally:
            platform._uname_cache = None 
Example #6
Source File: test_windows.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_special_pid(self):
        p = psutil.Process(4)
        self.assertEqual(p.name(), 'System')
        # use __str__ to access all common Process properties to check
        # that nothing strange happens
        str(p)
        p.username()
        self.assertTrue(p.create_time() >= 0.0)
        try:
            rss, vms = p.memory_info()[:2]
        except psutil.AccessDenied:
            # expected on Windows Vista and Windows 7
            if not platform.uname()[1] in ('vista', 'win-7', 'win7'):
                raise
        else:
            self.assertTrue(rss > 0) 
Example #7
Source File: test_parsers.py    From Computable with MIT License 6 votes vote down vote up
def test_file(self):

        # FILE
        if sys.version_info[:2] < (2, 6):
            raise nose.SkipTest("file:// not supported with Python < 2.6")
        dirpath = tm.get_data_path()
        localtable = os.path.join(dirpath, 'salary.table')
        local_table = self.read_table(localtable)

        try:
            url_table = self.read_table('file://localhost/' + localtable)
        except URLError:
            # fails on some systems
            raise nose.SkipTest("failing on %s" %
                                ' '.join(platform.uname()).strip())

        tm.assert_frame_equal(url_table, local_table) 
Example #8
Source File: State.py    From mongodb_consistent_backup with Apache License 2.0 6 votes vote down vote up
def __init__(self, base_dir, config, backup_time, seed_uri, argv=None):
        StateBase.__init__(self, base_dir, config)
        self.base_dir            = base_dir
        self.state['backup']     = True
        self.state['completed']  = False
        self.state['name']       = backup_time
        self.state['method']     = config.backup.method
        self.state['path']       = base_dir
        self.state['cmdline']    = argv
        self.state['config']     = config.dump()
        self.state['version']    = config.version
        self.state['git_commit'] = config.git_commit
        self.state['host']     = {
            'hostname': platform.node(),
            'uname':    platform.uname(),
            'python': {
                'build':   platform.python_build(),
                'version': platform.python_version()
            }
        }
        self.state['seed']       = {
            'uri':     seed_uri.str(),
            'replset': seed_uri.replset
        }
        self.init() 
Example #9
Source File: test_platform.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_uname_win32_ARCHITEW6432(self):
        # Issue 7860: make sure we get architecture from the correct variable
        # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
        # using it, per
        # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
        try:
            with test_support.EnvironmentVarGuard() as environ:
                if 'PROCESSOR_ARCHITEW6432' in environ:
                    del environ['PROCESSOR_ARCHITEW6432']
                environ['PROCESSOR_ARCHITECTURE'] = 'foo'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'foo')
                environ['PROCESSOR_ARCHITEW6432'] = 'bar'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'bar')
        finally:
            platform._uname_cache = None 
Example #10
Source File: prints.py    From pyinfra with MIT License 6 votes vote down vote up
def print_support_info():
    click.echo('''
    If you are having issues with pyinfra or wish to make feature requests, please
    check out the GitHub issues at https://github.com/Fizzadar/pyinfra/issues .
    When adding an issue, be sure to include the following:
''')

    click.echo('    System: {0}'.format(platform.system()))
    click.echo('      Platform: {0}'.format(platform.platform()))
    click.echo('      Release: {0}'.format(platform.uname()[2]))
    click.echo('      Machine: {0}'.format(platform.uname()[4]))
    click.echo('    pyinfra: v{0}'.format(__version__))
    click.echo('    Executable: {0}'.format(sys.argv[0]))
    click.echo('    Python: {0} ({1}, {2})'.format(
        platform.python_version(),
        platform.python_implementation(),
        platform.python_compiler(),
    )) 
Example #11
Source File: info_command.py    From airflow with Apache License 2.0 6 votes vote down vote up
def __str__(self):
        return (
            textwrap.dedent(
                """\
                Platform: [{os}, {arch}] {uname}
                Locale: {locale}
                Python Version: [{python_version}]
                Python Location: [{python_location}]
                """
            )
            .strip()
            .format(
                os=self.operating_system or "NOT AVAILABLE",
                arch=self.arch or "NOT AVAILABLE",
                uname=self.uname,
                locale=self.locale,
                python_version=self.python_version,
                python_location=self.python_location,
            )
        ) 
Example #12
Source File: cap_train.py    From chainerui with MIT License 6 votes vote down vote up
def chrome_driver():
    chrome_driver_path = cb.utils.get_chromedriver_path()
    chrome_driver_exe = os.path.join(
        chrome_driver_path, cb.utils.get_chromedriver_filename())
    if os.name != 'nt' and 'microsoft' in platform.uname().version.lower():
        chrome_driver_exe += '.exe'
    if not os.path.exists(chrome_driver_exe):
        msg = 'invalid driver module at \'{}\' error'.format(chrome_driver_exe)
        raise ValueError(msg)

    options = Options()
    options.add_argument('--headless')
    options.add_argument('--window-size=1200,1024')
    driver = webdriver.Chrome(
        chrome_options=options, executable_path=chrome_driver_exe)

    try:
        yield driver
    finally:
        driver.quit() 
Example #13
Source File: test_platform.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_uname_win32_ARCHITEW6432(self):
        # Issue 7860: make sure we get architecture from the correct variable
        # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
        # using it, per
        # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
        try:
            with support.EnvironmentVarGuard() as environ:
                if 'PROCESSOR_ARCHITEW6432' in environ:
                    del environ['PROCESSOR_ARCHITEW6432']
                environ['PROCESSOR_ARCHITECTURE'] = 'foo'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'foo')
                environ['PROCESSOR_ARCHITEW6432'] = 'bar'
                platform._uname_cache = None
                system, node, release, version, machine, processor = platform.uname()
                self.assertEqual(machine, 'bar')
        finally:
            platform._uname_cache = None 
Example #14
Source File: status.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def platform_info(self):
        """Collect the platform information.

        :returns: A dictionary of platform data
        """
        return platform.uname()._asdict() 
Example #15
Source File: vulmap-linux.py    From Vulmap with GNU General Public License v3.0 5 votes vote down vote up
def sendRequest(queryData):
	product_list = '"product_list": ' + queryData

	os = platform.uname()[1]
	arc = platform.uname()[4]

	json_request_data = '{'
	json_request_data += '"os": "' + os + '",'
	json_request_data += '"arc": "' + arc + '",'
	json_request_data += product_list
	json_request_data +=  '}'

	url = 'https://vulmon.com/scannerapi_vv211'
	body = 'querydata=' + json_request_data
	headers = {'Content-Type': 'application/x-www-form-urlencoded'}

	if pV == 2:
		if args.proxy:
			response = underConstruction()

		else:
			request = urllib2.Request(url, body, headers)
			result = urllib2.urlopen(request, timeout=5)
			response = json.loads(result.read())
	else:
		if args.proxy:
			if args.proxytype == 'https':
				proxy = args.proxy
				proxies = {'http' : 'https://'+proxy, 'https' : 'https://'+proxy}
				response = (requests.post(url, data=body, headers=headers, proxies=proxies, verify=False)).json()
			else:
				proxy = args.proxy
				proxies = {'http' : proxy, 'https' : proxy}
				response = (requests.post(url, data=body, headers=headers, proxies=proxies, verify=False)).json()
		else:
			response = (requests.post(url, data=body, headers=headers)).json()

	return response 
Example #16
Source File: utils.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def is_ccu():
    """Returns True when executed on a CCU device. Otherwise False is being returned."""
    if ".ccu" in platform.uname()[2]:
        return True

    try:
        for line in open("/etc/os-release"):
            if line == "NAME=Buildroot\n":
                return True
    except IOError:
        pass

    return False 
Example #17
Source File: test_platform.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_mac_ver(self):
        res = platform.mac_ver()

        try:
            import gestalt
        except ImportError:
            have_toolbox_glue = False
        else:
            have_toolbox_glue = True

        if have_toolbox_glue and platform.uname()[0] == 'Darwin':
            # We're on a MacOSX system, check that
            # the right version information is returned
            fd = os.popen('sw_vers', 'r')
            real_ver = None
            for ln in fd:
                if ln.startswith('ProductVersion:'):
                    real_ver = ln.strip().split()[-1]
                    break
            fd.close()
            self.assertFalse(real_ver is None)
            result_list = res[0].split('.')
            expect_list = real_ver.split('.')
            len_diff = len(result_list) - len(expect_list)
            # On Snow Leopard, sw_vers reports 10.6.0 as 10.6
            if len_diff > 0:
                expect_list.extend(['0'] * len_diff)
            self.assertEqual(result_list, expect_list)

            # res[1] claims to contain
            # (version, dev_stage, non_release_version)
            # That information is no longer available
            self.assertEqual(res[1], ('', '', ''))

            if sys.byteorder == 'little':
                self.assertIn(res[2], ('i386', 'x86_64'))
            else:
                self.assertEqual(res[2], 'PowerPC') 
Example #18
Source File: info_command.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, anonymizer: Anonymizer):
        self.operating_system = OperatingSystem.get_current()
        self.arch = Architecture.get_current()
        self.uname = platform.uname()
        self.locale = locale.getdefaultlocale()
        self.python_location = anonymizer.process_path(sys.executable)
        self.python_version = sys.version.replace("\n", " ") 
Example #19
Source File: benchmark.py    From signac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_doc(args):
    tmpdir = gettempdir() if args.root is None else args.root
    platform_doc = platform.uname()._asdict()
    return {'meta': {
        'tool': 'signac',
        'num_keys': args.num_keys,
        'num_doc_keys': args.num_doc_keys,
        'data_size': args.data_size,
        'seed': args.seed,
        'cached': args.cached,
        'categories': args.categories,
        'platform': platform_doc,
        'fstype': get_partition(tmpdir).fstype,
    }} 
Example #20
Source File: syslogfwder.py    From alerta-contrib with MIT License 5 votes vote down vote up
def run(self):

        count = 0
        while not self.shuttingdown:
            try:
                LOG.debug('Waiting for syslog messages...')
                ip, op, rdy = select.select([self.udp, self.tcp], [], [], LOOP_EVERY)
                if ip:
                    for i in ip:
                        if i == self.udp:
                            data, addr = self.udp.recvfrom(4096)
                            data = unicode(data, 'utf-8', errors='ignore')
                            LOG.debug('Syslog UDP data received from %s: %s', addr, data)
                        if i == self.tcp:
                            client, addr = self.tcp.accept()
                            data = client.recv(4096)
                            data = unicode(data, 'utf-8', errors='ignore')
                            client.close()
                            LOG.debug('Syslog TCP data received from %s: %s', addr, data)

                        alerts = self.parse_syslog(ip=addr[0], data=data)
                        for alert in alerts:
                            try:
                                self.api.send_alert(**alert)
                            except Exception as e:
                                LOG.warning('Failed to send alert: %s', e)

                    count += 1
                if not ip or count % 5 == 0:
                    LOG.debug('Send heartbeat...')
                    try:
                        origin = '{}/{}'.format('syslog', platform.uname()[1])
                        self.api.heartbeat(origin, tags=[__version__])
                    except Exception as e:
                        LOG.warning('Failed to send heartbeat: %s', e)

            except (KeyboardInterrupt, SystemExit):
                self.shuttingdown = True

        LOG.info('Shutdown request received...') 
Example #21
Source File: bot.py    From bot with MIT License 5 votes vote down vote up
def uname(): # Used to get system info for .uname command
    sysinfo = platform.uname()
    return sysinfo 
Example #22
Source File: udp.py    From nfcpy with European Union Public License 1.1 5 votes vote down vote up
def init(host, port):
    import platform
    device = Device(host, port)
    device._vendor_name = platform.uname()[0]
    device._device_name = "IP-Stack"
    device._chipset_name = "UDP"
    return device 
Example #23
Source File: nodehealth.py    From yin-yang-ranch with MIT License 5 votes vote down vote up
def get_sys_type(self):
        uname = platform.uname()
        if uname.system == 'Darwin':
            return 'Mac'
        elif uname.system == 'Linux':
            with open('/etc/os-release') as f:
                osrelease = f.read()
                if 'raspbian' in osrelease.lower():
                    return 'RPi'
                elif 'ubuntu' in osrelease.lower():
                    return 'Ubuntu'
                else:
                    return 'Linux'
        else:
            return 'Unknown' 
Example #24
Source File: uiQt.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def createQApp():
    """创建PyQt应用对象"""
    # 创建Qt应用对象
    qApp = QtWidgets.QApplication([])

    # 设置Qt的皮肤
    if globalSetting['darkStyle']:
        try:
            import qdarkstyle
            qApp.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        except :
            print("Unexpected error when import darkStyle:", sys.exc_info()[0])

    # 设置Windows底部任务栏图标
    if 'Windows' in platform.uname():
        import ctypes
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('vn.trader')

    # 设置Qt字体
    qApp.setFont(BASIC_FONT)

    # 设置Qt图标
    qApp.setWindowIcon(QtGui.QIcon(loadIconPath('vnpy.ico')))

    # 返回创建好的QApp对象
    return qApp 
Example #25
Source File: api_requestor.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _build_headers(cls, api_key=None, method="get", **kwargs):

        # The SDK's user agent info
        user_agent = _UA

        # (Optionally) the client's user agent info
        app_str = ""
        if codepost.app_info:
            app_str = cls._format_app_info(**codepost.app_info)
            user_agent += " " + app_str

        # Diagnostic information
        diag = {
            "sdk": _CODEPOST_SDK_VERSION,
            "lang": "python",
            "publisher": "codepost",
            "lang_version": _PY_VERSION,
            "platform": _platform.platform(),
            "uname": _platform.uname(),
            "app": app_str,
        }

        headers = {
            "Authorization": "Token {}".format(api_key),
            "User-Agent": user_agent,
            "X-codePost-SDK-User-Agent": _json.dumps(diag)
        }

        if method.upper() in ["POST", "PATCH"] and not "Content-Type" in headers:
            headers["Content-Type"] = "application/json"

        if method.upper() == "POST":
            headers.setdefault("Idempotency-Key", str(_uuid.uuid4()))

        return headers 
Example #26
Source File: util.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_systype():
    data = uname()
    type_ = data[0].lower()
    arch = data[4].lower() if data[4] else ""
    return "%s_%s" % (type_, arch) if arch else type_ 
Example #27
Source File: status.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def platform_info(self):
        """Collect the platform information.

        :returns: A dictionary of platform data
        """
        return platform.uname()._asdict() 
Example #28
Source File: test_excel.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_read_from_file_url(self, ext):

        # FILE
        localtable = os.path.join(self.dirpath, 'test1' + ext)
        local_table = read_excel(localtable)

        try:
            url_table = read_excel('file://localhost/' + localtable)
        except URLError:
            # fails on some systems
            import platform
            pytest.skip("failing on %s" %
                        ' '.join(platform.uname()).strip())

        tm.assert_frame_equal(url_table, local_table) 
Example #29
Source File: panhunt.py    From PANhunt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def output_report(search_dir, excluded_directories_string, all_files, total_files_searched, pans_found, output_file, mask_pans):

    pan_sep = u'\n\t'
    pan_report = u'PAN Hunt Report - %s\n%s\n' % (time.strftime("%H:%M:%S %d/%m/%Y"), '='*100)
    pan_report += u'Searched %s\nExcluded %s\n' % (search_dir, excluded_directories_string)
    pan_report += u'Command: %s\n' % (' '.join(sys.argv))
    pan_report += u'Uname: %s\n' % (' | '.join(platform.uname()))
    pan_report += u'Searched %s files. Found %s possible PANs.\n%s\n\n' % (total_files_searched, pans_found, '='*100)
    
    for afile in sorted([afile for afile in all_files if afile.matches]):
        pan_header = u'FOUND PANs: %s (%s %s)' % (afile.path, afile.size_friendly(), afile.modified.strftime('%d/%m/%Y'))
        print colorama.Fore.RED + filehunt.unicode2ascii(pan_header)
        pan_report += pan_header + '\n'
        pan_list = u'\t' + pan_sep.join([pan.__repr__(mask_pans) for pan in afile.matches])
        print colorama.Fore.YELLOW + filehunt.unicode2ascii(pan_list)
        pan_report += pan_list + '\n\n'
    
    if len([afile for afile in all_files if afile.type == 'OTHER']) <> 0:
        pan_report += u'Interesting Files to check separately:\n'
    for afile in sorted([afile for afile in all_files if afile.type == 'OTHER']):
        pan_report += u'%s (%s %s)\n' % (afile.path, afile.size_friendly(), afile.modified.strftime('%d/%m/%Y'))

    pan_report = pan_report.replace('\n', os.linesep)

    print colorama.Fore.WHITE + 'Report written to %s' % filehunt.unicode2ascii(output_file)
    filehunt.write_unicode_file(output_file, pan_report)
    add_hash_to_file(output_file) 
Example #30
Source File: common.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_file(self, datapath):
        localtable = datapath('io', 'parser', 'data', 'salaries.csv')
        local_table = self.read_table(localtable)

        try:
            url_table = self.read_table('file://localhost/' + localtable)
        except URLError:
            # fails on some systems
            pytest.skip("failing on %s" %
                        ' '.join(platform.uname()).strip())

        tm.assert_frame_equal(url_table, local_table)