Python module win32com on Linux

六眼飞鱼酱① 提交于 2019-12-09 13:44:09

问题


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:


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



来源:https://stackoverflow.com/questions/20927131/python-module-win32com-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!