Linux python可以检测它在哪个操作系统下运行吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4719063/
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-05 02:31:21  来源:igfitidea点击:

Can python detect which OS is it running under?

pythonwindowslinux

提问by Merlin

Can python detect OS and then contruct a if/else statement for File System.

python可以检测操作系统,然后为文件系统构造一个if/else语句。

I would need to replace C:\CobaltRCX\ in Fn string with the FileSys string.

我需要用 FileSys 字符串替换 Fn 字符串中的 C:\CobaltRCX\。

import os.path, csv
from time import strftime

if os.path.?????:## Windows
   FileSys = r"C:\working\" 
else:   ##linux   
   FileSys = r"\working\" 

y=(strftime("%y%m%d"))
Fn = (r"C:\working\Setup%s.csv" %y)

采纳答案by poke

I usually just use this:

我通常只使用这个:

import os
if os.name == 'nt':
    pass # Windows
else:
    pass # other (unix)

edit:

编辑:

Hopefully in response to your comments:

希望对您的意见作出回应:

from time import strftime
import os

if os.name == 'nt': # Windows
    basePath = 'C:\working\'
else:
    basePath = '/working/'

Fn = '%sSetup%s.csv' % ( basePath, strftime( '%y%m%d' ) )

回答by Elalfer

Use sys.platform. You can find more information here http://docs.python.org/library/platform.html

使用sys.platform. 您可以在此处找到更多信息http://docs.python.org/library/platform.html

回答by John Percival Hackworth

You could look at os.uname

你可以看看 os.uname

In [12]: os.uname()
Out[12]: 
('Darwin',
 'demitasse.local',
 '10.6.0',
 'Darwin Kernel Version 10.6.0: Wed Nov 10 18:13:17 PST 2010; root:xnu-1504.9.26~3/RELEASE_I386',
 'i386')

回答by Andrew

Yes.

是的。

>>> import os
>>> os.uname()
('Linux', 'ubuntu', '2.6.32-27-generic', '#49-Ubuntu SMP Thu Dec 2 00:51:09 UTC 2010', 'x86_64')
>>> system = os.uname()
>>> print system[0] + '/' + system[1]
Linux/ubuntu
>>> 

回答by Michael

For most usecases you should use the os.platformmodule. However if you need a more lean interface, try platinfo.

对于大多数用例,您应该使用该os.platform模块。但是,如果您需要更精简的界面,请尝试platinfo.

回答by Pawan Kumar

try this one:

试试这个:

    import platform
    platform.uname()

It works both on linux as well as windows. FYI: os.uname() will not work on windows, though it works on linux. Platform is generic.

它适用于 linux 和 windows。仅供参考:os.uname() 不适用于 Windows,但它适用于 linux。平台是通用的。

回答by user1259765

Here is what I just created the other day:

这是我前几天刚刚创建的:

CODE:

代码:

def GetUserPlatform():
    if sys.platform == 'win32':
        UsrWinVer = str(sys.getwindowsversion().major)
        print("Operating System: Windows " + UsrWinVer)
    else:
        print("Something else")

GetUserPlatform()

OUTPUT:

输出:

Operating System: Windows 10

操作系统:Windows 10

回答by Manindhar

import platform
print(platform.uname().system)

This will give you Windows, Linux, etc.

这将为您提供 Windows、Linux 等。