Renjith Thankachan
Renjith Thankachan

Reputation: 4346

Platform specific import in python

My work folder structure is as below,

.
├── hello_darwin.py
├── hello_linux.py
├── hello.py
└── hello_windows.py

hello.py contains common functions, while others contains platform specific code or function, when my module user imports

 from hello import common_function, spec_function

i need spec_function must be platform specific code, where spec_funtion name is masked to its module user.Is there any builting functions to do it or is there any other ways for this ?

Upvotes: 1

Views: 3114

Answers (2)

nick_gabpe
nick_gabpe

Reputation: 5805

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

For more info you can have look at docs

Upvotes: 3

Maurice Meyer
Maurice Meyer

Reputation: 18136

There is the platform module:

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 ...

Upvotes: 4

Related Questions