Python: What OS am I running on?

前端 未结 26 2041
野趣味
野趣味 2020-11-22 05:44

What do I need to look at to see whether I\'m on Windows or Unix, etc?

26条回答
  •  温柔的废话
    2020-11-22 06:25

    This solution works for both python and jython.

    module os_identify.py:

    import platform
    import os
    
    # This module contains functions to determine the basic type of
    # OS we are running on.
    # Contrary to the functions in the `os` and `platform` modules,
    # these allow to identify the actual basic OS,
    # no matter whether running on the `python` or `jython` interpreter.
    
    def is_linux():
        try:
            platform.linux_distribution()
            return True
        except:
            return False
    
    def is_windows():
        try:
            platform.win32_ver()
            return True
        except:
            return False
    
    def is_mac():
        try:
            platform.mac_ver()
            return True
        except:
            return False
    
    def name():
        if is_linux():
            return "Linux"
        elif is_windows():
            return "Windows"
        elif is_mac():
            return "Mac"
        else:
            return "" 
    

    Use like this:

    import os_identify
    
    print "My OS: " + os_identify.name()
    

提交回复
热议问题