When to use os.name, sys.platform, or platform.system?

后端 未结 5 460
感情败类
感情败类 2020-11-29 17:18

As far as I know, Python has 3 ways of finding out what operating system is running on:

  1. os.name
  2. sys.platform
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 17:58

    There is a thin line difference between platform.system() and sys.platform and interestingly for most cases platform.system() degenerates to sys.platform

    Here is what the Source Python2.7\Lib\Platform.py\system says

    def system():
    
        """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
    
            An empty string is returned if the value cannot be determined.
    
        """
        return uname()[0]
    
    def uname():
        # Get some infos from the builtin os.uname API...
        try:
            system,node,release,version,machine = os.uname()
        except AttributeError:
            no_os_uname = 1
    
        if no_os_uname or not filter(None, (system, node, release, version, machine)):
            # Hmm, no there is either no uname or uname has returned
            #'unknowns'... we'll have to poke around the system then.
            if no_os_uname:
                system = sys.platform
                release = ''
                version = ''
                node = _node()
                machine = ''
    

    Also per the documentation

    os.uname()

    Return a 5-tuple containing information identifying the current operating system. The tuple contains 5 strings: (sysname, nodename, release, version, machine). Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()).

    Availability: recent flavors of Unix.
    

提交回复
热议问题