简体   繁体   English

Linux上的Python模块win32com

[英]Python module win32com on Linux

I am writing some Python code that runs under multiple platforms. 我正在编写一些在多个平台下运行的Python代码。 Unfortunately under Win32, I have to support some COM functionalities. 不幸的是,在Win32下,我必须支持一些COM功能。

However these lines will fail under an Linux environment: 但是这些行在Linux环境下会失败:

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. 并且使用Win32 COM API的所有其他函数也将失败。 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 ? 确保根据平台不加载/导入某些代码并在接口客户端调用它们时给出错误消息/异常的标准方法是什么?

Use a try..except ImportError : 使用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. 您可以添加提供类似接口的特定于Linux的代码,或者您可以使用warnings模块告诉用户某些功能/功能不可用。


Alternatively, you could use an if-statement based on the value of sys.platform : 或者,你可以使用一个if-statement基于价值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') .) 对于跨平台代码可能很重要的其他值可以是os.name (可以等于'posix''nt''os2''ce''java''riscos' )或platform.architecture (这可能等于('32bit', 'ELF') 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM