4

I am writing some Python code that runs under multiple platforms. Unfortunately under Win32, I have to support some COM functionalities.

However these lines will fail under an Linux environment:

from pythoncom import PumpWaitingMessages
from pythoncom import Empty
from pythoncom import Missing
from pythoncom import com_error
import win32api

And all the other functions which are using the Win32 COM API will fail as well. What is the standard method to make sure that some code is not loaded/imported depending on the platform and give an error message/exception in the case they are called by the client of the interface ?

1 Answer 1

5

Use a try..except ImportError:

try:
    from pythoncom import PumpWaitingMessages
    from pythoncom import Empty
    from pythoncom import Missing
    from pythoncom import com_error
    import win32api
except ImportError:
    # handle exception

What to do when there is an exception is up to you. You could add Linux-specific code that provides an analogous interface, or you could use the warnings module to tell the user that certain functions/features are unavailable.


Alternatively, you could use an if-statement based on the value of sys.platform:

import sys
if sys.platform == "win32":
    ...
elif sys.platform == 'cygwin':
    ...
elif sys.platform[:5] == 'linux':
    ...
elif sys.platform == 'darwin':
    ...
else:
    ...

Other values which may be important for cross-platform code may be os.name (which could equal 'posix', 'nt', 'os2', 'ce', 'java', 'riscos'), or platform.architecture (which could equal things like ('32bit', 'ELF').)

Sign up to request clarification or add additional context in comments.

3 Comments

This solves the import, but the functions which are using the imports will still fail, isn't it ?
The functions that are Windows-specific should be placed inside the try-suite. Analogous functions that are Linux-specific should be placed in the except-suite.
Thanks, that is great, I am gonna try this asap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.