跨平台实践:python中如何检查当前操作系统

之前写的Android UI 自动化脚本及专项测试代码是在Windows上开发的,现在换mac了,有些地方需要根据不同系统环境进行兼容适配了,例如,

Windows:

python 复制代码
yaml_url = os.path.join(path, 'xx_ui_auto\\devices.yaml')

Mac:

python 复制代码
yaml_url = os.path.join(path, 'xx_ui_auto/devices.yaml')

在 python 中,可以使用内置的 os 模块的 os.name 或 platform.system() 来判断当前操作系统。以下是实现方法:

python 复制代码
import os
import platform

# 基础路径
path = "/Users/testmanzhang"

# 判断系统类型
if os.name == 'nt':  # Windows 系统
    yaml_url = os.path.join(path, 'xx_ui_auto\\devices.yaml')
elif os.name == 'posix':  # macOS 或 Linux 系统
    yaml_url = os.path.join(path, 'xx_ui_auto/devices.yaml')
else:
    raise RuntimeError("Unsupported operating system")

print(f"File path is: {yaml_url}")

或者

python 复制代码
import os
import platform

# 基础路径
path = "/Users/testmanzhang"

# 根据平台判断路径
system_name = platform.system()
if system_name == "Windows":
    yaml_url = os.path.join(path, 'xx_ui_auto\\devices.yaml')
elif system_name == "Darwin":  # macOS
    yaml_url = os.path.join(path, 'xx_ui_auto/devices.yaml')
elif system_name == "Linux":
    yaml_url = os.path.join(path, 'xx_ui_auto/devices.yaml')  # 假设 Linux 和 macOS 目录相同
else:
    raise RuntimeError("Unsupported operating system")

print(f"File path is: {yaml_url}")

为避免手动处理路径分隔符,推荐使用 os.path.join 或 pathlib,并统一使用正斜杠 /(兼容性更好)。

python 复制代码
from pathlib import Path
import platform

# 基础路径
path = Path("/Users/testmanzhang")

# 动态判断路径
system_name = platform.system()
if system_name == "Windows":
    yaml_url = path / "xx_ui_auto" / "devices.yaml"
elif system_name in ["Darwin", "Linux"]:  # macOS 或 Linux
    yaml_url = path / "xx_ui_auto" / "devices.yaml"
else:
    raise RuntimeError("Unsupported operating system")

print(f"File path is: {yaml_url}")

【总结】

os.name:

'nt': Windows

'posix': macOS 和 Linux

platform.system():

'Windows': Windows

'Darwin': macOS

'Linux': Linux

相关推荐
做怪小疯子14 小时前
华为笔试0429
python·numpy
Warson_L14 小时前
Dictionary
python
寒山李白16 小时前
解决 python-docx 生成的 Word 文档打开时弹出“无法读取内容“警告
python·word·wps·文档·docx·qoder
liang_jy16 小时前
Android SparseArray
android·源码
2501_9272835816 小时前
荣联汇智助力天津艺虹打造“软硬一体”智慧工厂,全流程自动化引领印刷包装行业数智变革
大数据·运维·数据仓库·人工智能·低代码·自动化
liang_jy17 小时前
Activity 启动流程扩展篇(一)—— startActivityInner 任务决策全解析
android·源码
2401_8323655217 小时前
JavaScript中rest参数(...args)取代arguments的优势
jvm·数据库·python
Sirius.z17 小时前
第J3周:DenseNet121算法详解
python
HXDGCL17 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
2301_7796224117 小时前
Go语言怎么用信号量控制并发_Go语言semaphore信号量教程【入门】
jvm·数据库·python