如何检查Python中的操作系统?

问题:如何检查Python中的操作系统?

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

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

如果脚本可以告诉您它是Mac,Windows还是Linux,那就可以了。我该如何检查?

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.

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


回答 0

您可以使用sys.platform

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

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

有关有效值,请参阅文档

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

You can use sys.platform:

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

sys.platform has finer granularity than sys.name.

For the valid values, consult the documentation.

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


回答 1

如果您想更精确地了解使用“ Linux”,“ Windows”或“ Darwin”(Mac)的平台,则应使用:

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

platform.system函数在uname内部使用。

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

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

The platform.system function uses uname internally.


回答 2

通过检查,您可以大致了解所使用的操作系统sys.platform

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

如果您想进行更深入的检查而又不想关心操作系统,那么也可以使用psutil

You can get a pretty coarse idea of the OS you’re using by checking 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 Information on unix-like OSes, or pywin32 for Windows.

There’s also psutil if you want to do more in-depth inspection without wanting to care about the OS.


回答 3

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

More detailed information are available in the platform module.


回答 4

您可以使用sys.platform