Python如何检测其运行的操作系统?

10 投票
10 回答
17973 浏览
提问于 2025-04-16 10:09

Python能不能识别操作系统,然后根据操作系统来构建一个if/else语句,用于文件系统的判断。

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

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)

10 个回答

5

使用 sys.platform。你可以在这里找到更多信息 http://docs.python.org/library/platform.html

6

可以查看这里: https://stackoverflow.com/a/58689984/3752715

import platform 
plt = platform.system()

if   plt == "Windows":   print("Your system is Windows")
elif plt == "Linux":     print("Your system is Linux")
elif plt == "Darwin":    print("Your system is MacOS")
else:                    print("Unidentified system")

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

22

我通常就用这个:

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

补充:

希望能回应你们的评论:

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' ) )

撰写回答