Pergunta

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 ?

Foi útil?

Solução

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top