Linux 如何在 Python 中检查操作系统?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8220108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:24:36  来源:igfitidea点击:

How do I check the operating system in Python?

pythonlinuxoperating-system

提问by kolek

I want to check the operating system (on the computer where the script runs).

我想检查操作系统(在运行脚本的计算机上)。

I know I can use os.system('uname -o')in Linux, but it gives me a message in the console, and I want to write to a variable.

我知道我可以os.system('uname -o')在 Linux中使用,但是它在控制台中给了我一条消息,我想写入一个变量。

It will be okay if the script can tell if it is Mac, Windows or Linux. How can I check it?

如果脚本可以判断它是 Mac、Windows 还是 Linux,那就没问题了。我该如何检查?

采纳答案by the wolf

You can use sys.platform:

您可以使用sys.platform

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

sys.platformhas finer granularity than sys.name.

sys.platform具有比 更细的粒度sys.name

For the valid values, consult the documentation.

有关有效值,请参阅文档

See also the answer to “What OS am I running on?”

另请参阅“我在运行什么操作系统?”的答案

回答by Ondrej Slinták

You can use sys.platform.

您可以使用sys.platform.

回答by Nick Bastin

You can get a pretty coarse idea of the OS you're using by checking sys.platform.

您可以通过检查sys.platform.

Once you have that information you can use it to determine if calling something like os.uname()is appropriate to gather more specific information. You could also use something like Python System Informationon unix-like OSes, or pywin32for Windows.

获得该信息后,您可以使用它来确定调用类似的方法os.uname()是否适合收集更具体的信息。您还可以在类 Unix 操作系统上使用Python 系统信息,或在 Windows上使用pywin32

There's also psutilif you want to do more in-depth inspection without wanting to care about the OS.

如果您想在不想关心操作系统的情况下进行更深入的检查,也可以使用psutil

回答by Sven Marnach

More detailed information are available in the platformmodule.

platform模块中提供了更详细的信息。

回答by Laurent LAPORTE

If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:

如果您想知道您在“Linux”、“Windows”或“Darwin”(Mac)之外的哪个平台上使用,但不更精确,您应该使用:

>>> import platform
>>> platform.system()
'Linux'  # or 'Windows'/'Darwin'

The platform.systemfunction uses unameinternally.

platform.system函数uname内部使用。