Python 中特定于平台的导入

问题描述 投票:0回答:2

我的工作文件夹结构如下,

.
├── hello_darwin.py
├── hello_linux.py
├── hello.py
└── hello_windows.py
当我的模块用户导入时,

hello.py
包含常用功能,而其他则包含特定于平台的代码或功能

 from hello import common_function, spec_function

我需要spec_function必须是平台特定的代码,其中

spec_funtion
名称对其模块用户进行屏蔽。是否有任何构建函数可以做到这一点,或者有其他方法吗?

python python-2.7 python-3.x
2个回答
4
投票

平台模块:

import platform

if platform.system().lower().startswith('win'):
    # import windows specific modules
elif platform.system().lower().startswith('lin'):
    # import linux specific modules
elif platform.system().lower().startswith('dar'):
    # import ...

3
投票
from sys import platform
if platform.startswith('win'):
    #windows import
elif platform.startswith('lin'):
    #linux import
elif platform.startswith('dar'):
    #MacOS import
else:
    #some another OS import

有关更多信息,您可以查看docs

© www.soinside.com 2019 - 2024. All rights reserved.