Python platform 模块,uname() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用platform.uname()

项目:stephanie-va    作者:SlapBot    | 项目源码 | 文件源码
def tell_system_status(self):
        import psutil
        import platform
        import datetime

        os, name, version, _, _, _ = platform.uname()
        version = version.split('-')[0]
        cores = psutil.cpu_count()
        cpu_percent = psutil.cpu_percent()
        memory_percent = psutil.virtual_memory()[2]
        disk_percent = psutil.disk_usage('/')[3]
        boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
        running_since = boot_time.strftime("%A %d. %B %Y")
        response = "I am currently running on %s version %s.  " % (os, version)
        response += "This system is named %s and has %s CPU cores.  " % (name, cores)
        response += "Current disk_percent is %s percent.  " % disk_percent
        response += "Current CPU utilization is %s percent.  " % cpu_percent
        response += "Current memory utilization is %s percent. " % memory_percent
        response += "it's running since %s." % running_since
        return response
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def doFingerprints(self, nomfichier) :
        try :
            fichier = open(nomfichier, "w")
        except IOError :
            print "No such file " + nomfichier 
            sys.exit(-1)

        print "++ Begin Generating Fingerprints in " + nomfichier
        fichier.write("# Generating Fingerprints for :\n# ")
        for i in platform.uname():
            fichier.write(i + " ")

        fichier.write('\n')

        temps = strftime('%c', gmtime())
        fichier.write("# " + temps + '\n')

        self.ssyscalls.doFingerprints(fichier)

        fichier.close()
        print "++ Keep this fingerprints in safe !"
        print "++ End Generating Fingerprints"
项目:mongodb_consistent_backup    作者:Percona-Lab    | 项目源码 | 文件源码
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()
项目:sequana    作者:sequana    | 项目源码 | 文件源码
def on_cluster(pattern=["tars-"]):
    """Used to check if we are on a cluster

    "tars-" is the name of a cluster's hostname.
    Change or append the argument **pattern** with your cluster's hostname

    :param str pattern: a list of names (strings) or a string

    """
    if isinstance(pattern, str):
        pattern = [pattern]

    for this in pattern:
        if platform.uname().node.startswith(this):
            return True
        else:
            return False
项目:forgetmenot    作者:eavalenzuela    | 项目源码 | 文件源码
def lootme_windows(outfiles):
    try:
        import winreg
        # to be filled later
    except:
        print('winreg module not present')

    hostloot = ((platform.uname()[1])+"_loot.txt")
    outfiles.append(hostloot)
    with open(hostloot, 'w') as outFile:
        # gather machine info
        machine_info(outFile)
        # gather extended machine info 
        machine_info_extra_win(outFile)
        # gather user info
        user_info_win(outFile)
        # gather network info
        network_info_win(outFile)
        # gather log file IPs
        logfile_ips(outFile)

    return outfiles
### lootme_windows --end--

### lootme_linux --start--
项目:forgetmenot    作者:eavalenzuela    | 项目源码 | 文件源码
def userfiles_list_lin(outfiles):
    userdirs = os.listdir('/home/')
    userfiles = (platform.uname()[1]+'_userFiles.txt')
    outfiles.append(userfiles)
    with open(userfiles, 'w') as ufs:
        ufs.write('\nFiles discovered:')
        for d in userdirs:
            for path, subdirs, files in os.walk('/home/'+d):
                for name in files:
                    # search user directories for specified filetypes:
                    #   pdf, txt, doc(x)
                    if re.search('[.]*\.pdf', name) or re.search('[.]*\.txt', name) or re.search('[.]*\.doc[.]{1}', name):
                        ufs.write('\n'+os.path.join(path, name)+'\n')
    return outfiles
### User files list --end--

###  Log file IPs --start--
项目:mx    作者:graalvm    | 项目源码 | 文件源码
def get_arch():
    machine = platform.uname()[4]
    if machine in ['aarch64']:
        return 'aarch64'
    if machine in ['amd64', 'AMD64', 'x86_64', 'i86pc']:
        return 'amd64'
    if machine in ['sun4v', 'sun4u', 'sparc64']:
        return 'sparcv9'
    if machine == 'i386' and get_os() == 'darwin':
        try:
            # Support for Snow Leopard and earlier version of MacOSX
            if subprocess.check_output(['sysctl', '-n', 'hw.cpu64bit_capable']).strip() == '1':
                return 'amd64'
        except OSError:
            # sysctl is not available
            pass
    abort('unknown or unsupported architecture: os=' + get_os() + ', machine=' + machine)
项目:NebulaSolarDash    作者:toddlerya    | 项目源码 | 文件源码
def get_platform(self):
        """
        Get the OS name, hostname and kernel
        """
        try:
            osname = " ".join(platform.linux_distribution())
            uname = platform.uname()

            if osname == ' ':
                osname = uname[0]

            data = {'osname': osname, 'hostname': uname[1], 'kernel': uname[2]}

        except Exception as err:
            print err
            data = str(err)

        return data

    # ----------------end: ???????????-----------------

    # ----------------start: ???????????????-----------------
项目:avocado-misc-tests    作者:avocado-framework-tests    | 项目源码 | 文件源码
def setUp(self):
        '''
        Install the packages
        '''
        # Check for basic utilities
        smm = SoftwareManager()
        detected_distro = distro.detect()
        kernel_ver = platform.uname()[2]
        deps = ['gcc', 'make']
        if 'Ubuntu' in detected_distro.name:
            deps.extend(['linux-tools-common', 'linux-tools-%s'
                         % kernel_ver])
        # FIXME: "redhat" as the distro name for RHEL is deprecated
        # on Avocado versions >= 50.0.  This is a temporary compatibility
        # enabler for older runners, but should be removed soon
        elif detected_distro.name in ['rhel', 'SuSE', 'fedora', 'redhat']:
            deps.extend(['perf'])
        else:
            self.cancel("Install the package for perf supported by %s"
                        % detected_distro.name)
        for package in deps:
            if not smm.check_installed(package) and not smm.install(package):
                self.cancel('%s is needed for the test to be run' % package)
项目:avocado-misc-tests    作者:avocado-framework-tests    | 项目源码 | 文件源码
def setUp(self):
        """
        Verify it is baremetal
        Install the cpupower tool
        """
        if not os.path.exists('/proc/device-tree/ibm,opal/power-mgt'):
            self.cancel("Supported only on Power Non Virutalized environment")
        smm = SoftwareManager()
        detected_distro = distro.detect()
        if 'Ubuntu' in detected_distro.name:
            deps = ['linux-tools-common', 'linux-tools-%s'
                    % platform.uname()[2]]
        else:
            deps = ['kernel-tools']
        for package in deps:
            if not smm.check_installed(package) and not smm.install(package):
                self.cancel('%s is needed for the test to be run' % package)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
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)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_read_from_file_url(self):

        # FILE
        if sys.version_info[:2] < (2, 6):
            raise nose.SkipTest("file:// not supported with Python < 2.6")

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

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

        tm.assert_frame_equal(url_table, local_table)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
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)
项目:dataplicity-agent    作者:wildfoundry    | 项目源码 | 文件源码
def _init(self):
        try:
            log.info('dataplicity %s', __version__)
            log.info('uname=%s', ' '.join(platform.uname()))

            self.remote = jsonrpc.JSONRPC(self.rpc_url)
            self.serial = self._read(constants.SERIAL_LOCATION)
            self.auth_token = self._read(constants.AUTH_LOCATION)
            self.poll_rate_seconds = 60
            self.disk_poll_rate_seconds = 60 * 60
            self.next_disk_poll_time = time.time()

            log.info('m2m=%s', self.m2m_url)
            log.info('api=%s', self.rpc_url)
            log.info('serial=%s', self.serial)
            log.info('poll=%s', self.poll_rate_seconds)

            self.m2m = M2MManager.init(self, m2m_url=self.m2m_url)
            self.port_forward = PortForwardManager.init(self)

        except:
            log.exception('failed to initialize client')
            raise
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
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
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
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
项目:Oyster    作者:Wykleph    | 项目源码 | 文件源码
def get_sys_info():
    info = """
Machine: {}\nVersion: {}
Platform: {}\nNode: {}\nUname: {}\nSystem: {}
Processor: {}\n\nHost Name: {}\nFQDN: {}\n
""".format(
        platform.machine(),
        platform.version(),
        platform.platform(),
        platform.node(),
        platform.uname(),
        platform.system(),
        platform.processor(),
        socket.gethostname(),
        socket.getfqdn()
    )
    return info
项目:bot-mv-telegram    作者:awuth    | 项目源码 | 文件源码
def uptime_string(startup_time_in_seconds, last_error_time):
    # Machine info
    uname = platform.uname()
    uptime_seconds = uptime.uptime()
    # Delta uptime in human readable format
    uptime_message = str(timedelta(seconds=uptime_seconds))
    # Time now
    now = time.time()
    delta = now - startup_time_in_seconds
    bot_uptime = str(timedelta(seconds=int(delta)))

    # Make messsge
    message = ""
    message += "\U0001F4BB Running on " + uname[0] + " " + uname[2] + " " + uname[4] + "\n"
    message += "\U0000231B Machine Uptime: " + uptime_message + "\n"
    message += "\U0001F916 Bot uptime: " + bot_uptime + "\n"

    return message
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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)
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
def _get_os_type():
    os_type = OSType.unknown[0]

    # Figure out the general OS type
    uname = platform.system().strip().strip('"').strip("'").strip().lower()
    if 'beos' in uname or 'haiku' in uname:
        os_type = OSType.BeOS[0]
    elif 'bsd' in uname or 'gnu/kfreebsd' in uname:
        os_type = OSType.BSD[0]
    elif 'cygwin' in uname:
        os_type = OSType.Cygwin[0]
    elif 'darwin' in uname:
        os_type = OSType.MacOS[0]
    elif 'linux' in uname:
        os_type = OSType.Linux[0]
    elif 'solaris' in uname or 'sunos' in uname:
        os_type = OSType.Solaris[0]
    elif 'windows' in uname:
        os_type = OSType.Windows[0]

    return os_type
项目:mbuild    作者:intelxed    | 项目源码 | 文件源码
def __str__(self):
        """Print out the environment"""
        s = []
        s.append("BUILD_CPU:")
        s.append(self.env['build_cpu'])
        s.append("HOST_CPU:")
        s.append(self.env['host_cpu'])
        s.append("\nBUILD_OS: ")
        s.append(self.env['build_os'])
        s.append("\nHOST_OS: ")
        s.append(self.env['host_os'])
        s.append("\nUNAME: ")
        s.append(str(self.env['uname']))
        s.append("\nHOSTNAME: ")
        s.append(self.env['hostname'])
        s.append("\nSYSTEM: ")
        s.append(self.env['system'])
        s.append("\nDICTIONARY:\n")
        for k,v in iter(self.env.items()):
            s.append("\t")
            s.append(k)
            s.append("->")
            s.append(str(v))
            s.append("\n")
        return ''.join(s)
项目:mbuild    作者:intelxed    | 项目源码 | 文件源码
def verbose_startup(self):
        if self._emitted_startup_msg:
            return
        self._emitted_startup_msg = True
        if verbose(1):
            msgb("INVOKED", " ".join(sys.argv))
            msgb("START TIME", self.env['start_time_str'])
            msgb("CURRENT DIRECTORY", os.getcwd())

            msgb('UNAME', str(self.env['uname']).replace(':','_'))
            msgb('SYSTEM', self.env['system'])
            msgb('HOSTNAME', self.env['hostname'])
            msgb("BUILD_OS", self.env['build_os'])
            msgb("BUILD_CPU", self.env['build_cpu'])
            msgb("HOST_OS", self.env['host_os'])
            msgb("HOST_CPU", self.env['host_cpu'])
项目:AutoML5    作者:djajetic    | 项目源码 | 文件源码
def show_platform():
    ''' Show information on platform'''
    swrite('\n=== SYSTEM ===\n\n')
    try:
        linux_distribution = platform.linux_distribution()
    except:
        linux_distribution = "N/A"
    swrite("""
    dist: %s
    linux_distribution: %s
    system: %s
    machine: %s
    platform: %s
    uname: %s
    version: %s
    mac_ver: %s
    memory: %s
    number of CPU: %s
    """ % (
    str(platform.dist()),
    linux_distribution,
    platform.system(),
    platform.machine(),
    platform.platform(),
    platform.uname(),
    platform.version(),
    platform.mac_ver(),
    psutil.virtual_memory(),
    str(psutil.cpu_count())
    ))
项目:Starfish    作者:BillWang139967    | 项目源码 | 文件源码
def uname(self):
        p = subprocess.Popen(shlex.split('uname -i'), stdout=subprocess.PIPE, close_fds=True)
        hwplatform = p.stdout.read().strip()
        p.wait()

        uname = platform.uname()
        return {
            'kernel_name': uname[0],
            'node': uname[1],
            'kernel_release': uname[2],
            'kernel_version': uname[3],
            'machine': uname[4],
            'processor': uname[5],
            'platform': hwplatform,
        }
项目:docklet    作者:unias    | 项目源码 | 文件源码
def collect_osinfo(self):
        uname = platform.uname()
        osinfo = {}
        osinfo['platform'] = platform.platform()
        osinfo['system'] = uname.system
        osinfo['node'] = uname.node
        osinfo['release'] = uname.release
        osinfo['version'] = uname.version
        osinfo['machine'] = uname.machine
        osinfo['processor'] = uname.processor
        return osinfo

    # run function in the thread
项目:BitBot    作者:crack00r    | 项目源码 | 文件源码
def __init__(self, session_user_id):
        """session_user_id should either be a string or another Session.
           Note that if another session is given, only parameters like
           those required to init a connection will be copied.
        """
        # These values will NOT be saved
        if isinstance(session_user_id, JsonSession):
            self.session_user_id = None

            # For connection purposes
            session = session_user_id
            self.device_model = session.device_model
            self.system_version = session.system_version
            self.app_version = session.app_version
            self.lang_code = session.lang_code
            self.system_lang_code = session.system_lang_code
            self.lang_pack = session.lang_pack

        else:  # str / None
            self.session_user_id = session_user_id

            system = platform.uname()
            self.device_model = system.system if system.system else 'Unknown'
            self.system_version = system.release if system.release else '1.0'
            self.app_version = '1.0'  # '0' will provoke error
            self.lang_code = 'en'
            self.system_lang_code = self.lang_code
            self.lang_pack = ''

        # Cross-thread safety
        self._lock = Lock()

        # These values will be saved
        self.server_address = '91.108.56.165'
        self.port = 443
        self.auth_key = None
        self.id = utils.generate_random_long(signed=False)
        self._sequence = 0
        self.salt = 0  # Unsigned long
        self.time_offset = 0
        self._last_msg_id = 0  # Long
项目:cbapi-python    作者:carbonblack    | 项目源码 | 文件源码
def __init__(self, cb):
        super(RabbitMQEventSource, self).__init__()
        self.daemon = True

        self._closing = False
        self._connection = None
        self._channel = None
        self._closing = False
        self._consumer_tag = None
        self._auto_ack = True
        self._consuming = False

        self._cb = cb
        creds = cb.credentials

        if not creds.rabbitmq_pass:
            error_text = "RabbitMQEventSource requires credentials for the event bus. Make sure that\n" + \
                         "rabbitmq_pass, rabbitmq_user, rabbitmq_host, and rabbitmq_port are defined\n" + \
                         "in the credential file"

            if cb.credential_profile_name:
                error_text += " for profile '{0}'.".format(cb.credential_profile_name)

            raise CredentialError(error_text)

        self._url = "amqp://{0}:{1}@{2}:{3}".format(creds.rabbitmq_user, creds.rabbitmq_pass, creds.rabbitmq_host,
                                                    creds.rabbitmq_port)

        self.QUEUE = "cbapi-event-handler-{0}-{1}".format(platform.uname()[1], os.getpid())
        self.EXCHANGE = "api.events"
        self.ROUTING_KEYS = registry.event_types
        self.EXCHANGE_TYPE = "topic"
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def main():
    global canvas
    root = Tk()
    root.title('Tetrahedron')
    root.geometry('+0+0')

    init()

    canvas = Canvas(root, width=400, height=400, background=bgColor)
    canvas.pack(fill=BOTH,expand=YES)               
    canvas.bind("<Button-1>", cbClicked)
    canvas.bind("<B1-Motion>", cbMottion)
    canvas.bind("<Configure>", resize)

    from platform import uname
    os = uname()[0]
    if ( os == "Linux" ):
         canvas.bind('<Button-4>', wheelUp)      # X11
         canvas.bind('<Button-5>', wheelDown)
    elif ( os == "Darwin" ):
         canvas.bind('<MouseWheel>', wheel)      # MacOS
    else: 
         canvas.bind_all('<MouseWheel>', wheel)  # windows

    drawTet(tet,tetColor)

    mainloop()
项目:RSPET    作者:panagiks    | 项目源码 | 文件源码
def sys_info():
    """Get platform info."""
    import platform
    sys_info_tup = platform.uname()
    return (sys_info_tup[0], sys_info_tup[1])
项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
def get_system_info():
    try:
        if platform.system() == "Windows":
            username = os.environ["USERNAME"]
            sysname, nodename, release, version, machine, _ = platform.uname()
        else:
            username = getpass.getuser()
            sysname, nodename, release, version, machine = os.uname()
    except Exception as e:
        logger.error(e)
        username = 'unknown'
        sysname, nodename, release, version, machine = sys.platform,'unknown','unknown','unknown','unknown'

    return "User: {}, Platform: {}, Machine: {}, Release: {}, Version: {}".format(username,sysname,nodename,release,version)
项目:pythonVSCode    作者:DonJayamanne    | 项目源码 | 文件源码
def __init__(self):
        self.default_sys_path = sys.path
        self._input = io.open(sys.stdin.fileno(), encoding='utf-8')
        if (os.path.sep == '/') and (platform.uname()[2].find('Microsoft') > -1):
            # WSL; does not support UNC paths
            self.drive_mount = '/mnt/'
        elif sys.platform == 'cygwin':
            # cygwin
            self.drive_mount = '/cygdrive/'
        else:
            # Do no normalization, e.g. Windows build of Python.
            # Could add additional test: ((os.path.sep == '/') and os.path.isdir('/mnt/c'))
            # However, this may have more false positives trying to identify Windows/*nix hybrids
            self.drive_mount = ''
项目:AutoML4    作者:djajetic    | 项目源码 | 文件源码
def show_platform():
    ''' Show information on platform'''
    swrite('\n=== SYSTEM ===\n\n')
    try:
        linux_distribution = platform.linux_distribution()
    except:
        linux_distribution = "N/A"
    swrite("""
    dist: %s
    linux_distribution: %s
    system: %s
    machine: %s
    platform: %s
    uname: %s
    version: %s
    mac_ver: %s
    memory: %s
    number of CPU: %s
    """ % (
    str(platform.dist()),
    linux_distribution,
    platform.system(),
    platform.machine(),
    platform.platform(),
    platform.uname(),
    platform.version(),
    platform.mac_ver(),
    psutil.virtual_memory(),
    str(psutil.cpu_count())
    ))
项目:sequana    作者:sequana    | 项目源码 | 文件源码
def test_oncluster():
    assert on_cluster() is False

    import platform
    name = platform.uname().node
    assert on_cluster([name]) is True
    assert on_cluster(name) is True
项目:CVE-2016-6366    作者:RiskSense-Ops    | 项目源码 | 文件源码
def pacemaker(self, timeout=60):
    #   This is a stand-alone heartbeat generator.  To pulse from your own control loop,
    #   call your AbstractLog subclass instance event handler (e.g. AbstractLog['event']()
        def __target(timeout=60):
            if platform.uname()[0].lower() == "windows":
                import win32con
                import win32event
                self.running = True
                kill = win32event.CreateEvent(None, 1, 0, None)
                pulse = win32event.CreateWaitableTimer(None, 0, None)
                win32event.SetWaitableTimer(pulse, 0, timeout*1000, None, None, False)
                while(self.running):
                    try:
                        result = win32event.WaitForMultipleObjects([kill, pulse], False, 1000)

                        # if kill signal received, break loop
                        if(result == win32con.WAIT_OBJECT_0): break
                        # elif timeout has passed, generate a pulse
                        elif(result == win32con.WAIT_OBJECT_0 + 1): self['event']()
                    except:
                        self.notifyOfError("Pacemaker shutdown.  Heartbeats will not be generated.")
                        win32event.SetEvent(kill)
            elif self.options['Verbose']: print "Pacemaker only supported in Windows at this time. " 

        try:
            self.thread = threading.Thread(target=__target, args=(timeout,) )
            self.thread.start()
        except:
            self.notifyOfError("Pacemaker thread exception.  Heartbeats will not be generated.")
项目:forgetmenot    作者:eavalenzuela    | 项目源码 | 文件源码
def lootme_linux(outfiles):

    hostloot = (platform.uname()[1]+'_loot.txt')
    outfiles.append(hostloot)
    with open(hostloot, 'w') as outFile:
        # gather machine info
        machine_info(outFile)
        # gather user info
        user_info_lin(outFile)
        # gather network info
        network_info_lin(outFile)
        # gather disk info
        disk_info_lin(outFile)
        # gather process info
        process_info_lin(outFile)
        # search user files for extractable data
        userdata_extract_lin(outFile)
        # search for list of user files
        outfiles = userfiles_list_lin(outfiles)
        # search entire os for .log files, and grab all unique IP addresses
        logfile_ips(outFile)

    return outfiles
### lootme_linux --end--

### Machine info --start--
项目:forgetmenot    作者:eavalenzuela    | 项目源码 | 文件源码
def machine_info(outFile):
    # Dump machine information
    outFile.write('Machine info:\n')
    outFile.write(platform.uname()[1]+'\n'+platform.system()+'\n'+platform.release()+'\n'+platform.version()+'\n')
    # Dump environment variables
    outFile.write("Environment vars:\n"+str(os.environ)+'\n')
### Machine info --end--

### Machine info extra Windows --start--
项目:automl_gpu    作者:abhishekkrthakur    | 项目源码 | 文件源码
def show_platform():
    ''' Show information on platform'''
    swrite('\n=== SYSTEM ===\n\n')
    try:
        linux_distribution = platform.linux_distribution()
    except:
        linux_distribution = "N/A"
    swrite("""
    dist: %s
    linux_distribution: %s
    system: %s
    machine: %s
    platform: %s
    uname: %s
    version: %s
    mac_ver: %s
    memory: %s
    number of CPU: %s
    """ % (
    str(platform.dist()),
    linux_distribution,
    platform.system(),
    platform.machine(),
    platform.platform(),
    platform.uname(),
    platform.version(),
    platform.mac_ver(),
    psutil.virtual_memory(),
    str(psutil.cpu_count())
    ))
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
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)      

    #----------------------------------------------------------------------
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def main():
    """?????"""
    # ??sys???????????????utf8
    reload(sys)
    sys.setdefaultencoding('utf8')

    # ??Windows???????
    if 'Windows' in platform.uname() :
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('InplusTrader')

    # ???Qt????
    app = QtGui.QApplication(sys.argv)
    app.setWindowIcon(QtGui.QIcon(ICON_FILENAME))
    app.setFont(BASIC_FONT)

    # ??Qt???
    try:
        f = file(SETTING_FILENAME)
        setting = json.load(f)    
        if setting['darkStyle']:
            import qdarkstyle
            app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))
    except:
        pass

    # ????????????
    mainEngine = MainEngine()
    mainWindow = MainWindow(mainEngine, mainEngine.eventEngine)
    mainWindow.showMaximized()

    # ???????Qt????
    sys.exit(app.exec_())
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def slave_Info(netsettings):
    sysname, nodename, release, version, machine, processor = platform.uname()
    slave = netrender.model.RenderSlave()
    slave.name = nodename
    slave.stats = sysname + " " + release + " " + machine + " " + processor
    if netsettings.slave_tags:
        slave.tags = set(netsettings.slave_tags.split(";"))

    if netsettings.slave_bake:
        slave.tags.add(netrender.model.TAG_BAKING)

    if netsettings.slave_render:
        slave.tags.add(netrender.model.TAG_RENDER)

    return slave
项目:sparrow    作者:BillWang139967    | 项目源码 | 文件源码
def uname(self):
        p = subprocess.Popen(shlex.split('uname -i'), stdout=subprocess.PIPE, close_fds=True)
        hwplatform = p.stdout.read().strip()
        p.wait()

        uname = platform.uname()
        return {
            'kernel_name': uname[0],
            'node': uname[1],
            'kernel_release': uname[2],
            'kernel_version': uname[3],
            'machine': uname[4],
            'processor': uname[5],
            'platform': hwplatform,
        }
项目:nfcpy    作者:nfcpy    | 项目源码 | 文件源码
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
项目:MyPythonLib    作者:BillWang139967    | 项目源码 | 文件源码
def uname(self):
        p = subprocess.Popen(shlex.split('uname -i'), stdout=subprocess.PIPE, close_fds=True)
        hwplatform = p.stdout.read().strip()
        p.wait()

        uname = platform.uname()
        return {
            'kernel_name': uname[0],
            'node': uname[1],
            'kernel_release': uname[2],
            'kernel_version': uname[3],
            'machine': uname[4],
            'processor': uname[5],
            'platform': hwplatform,
        }