【问题标题】:Detect OS with python用python检测操作系统
【发布时间】:2019-10-04 06:19:09
【问题描述】:

我四处寻找解决问题的方法,我能找到的最好的方法是:

from sys import platform
if platform == "linux" or platform == "linux2":
    # linux
elif platform == "darwin":          
    # OS X
elif platform == "win32":             
    # Windows...

有人知道我如何将 Linux PC 与 android 区分开来,因为 android 是基于 Linux 的。如果这是可能的,我怎么能将 Mac OS 与 iOS 区分开来

【问题讨论】:

    标签: python-3.x operating-system differentiation


    【解决方案1】:

    使用platform 模块:

    import platform
    print(platform.system())
    print(platform.release())
    print(platform.version())
    

    请注意,在 Mac 上运行的系统将为 platform.system() 返回“Darwin”

    platform.platform()会返回极其详细的数据,比如

    'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'
    

    【讨论】:

      【解决方案2】:

      根据我的个人经验,os.uname() 一直是我的最爱。 uname 函数只存在于基于 Linux 的系统中。以与此类似的方法使用该函数,是检测您是否正在运行 Windows 系统的好方法:

      import os
      
      try:
          test = os.uname()
          if test[0] == "Linux":
              do something here.
      execpt AttributeError:
          print("Assuming windows!")
          do some other stuff here.
      
      

      我希望这会有所帮助!

      【讨论】:

        【解决方案3】:

        你可以查看我的 github 仓库 https://github.com/sk3pp3r/PyOS 并使用 pyos.py 脚本

        import platform 
        plt = platform.system()
        
        if plt == "Windows":
            print("Your system is Windows")
            # do x y z
        elif plt == "Linux":
            print("Your system is Linux")
            # do x y z
        elif plt == "Darwin":
            print("Your system is MacOS")
            # do x y z
        else:
            print("Unidentified system")
        

        【讨论】:

          【解决方案4】:

          如果你只想使用标准库,我建议你看看https://docs.python.org/3/library/sys.html#sys.platform

          例子:

          import sys
          
          if sys.platform.startswith('linux'):
              # Linux specific procedures
          elif sys.platform.startswith('darwin'):
              # MacOs specific procedures
          elif sys.platform.startswith('win32'):
              # Windows specific procedures
          

          【讨论】: