我有一个通常在Windows下运行并使用win32com模块的类.我也有这个类的模拟版本,无论是用于测试还是用于演示,都是从原始版本导入的,应该能够在任何地方运行.所以,就像这样,在两个文件中:
import win32com.client
class basic():
def local_instance(self):
# called once during setup of execution
res = win32com.client.Dispatch('Foo.Bar')
def res_attrib(self):
# called repeatedly by threads; must re-instantiate COM obj
return win32com.client.Dispatch('Foo.Bar').Attribute
def otherstuf(self):
...
=======================
from basic import basic
class mock(basic):
def local_instance(self):
res = mock_foobar() # mock implementation with .Attribute
def res_attrib(self):
return res.Attribute # mock implementation, this is OK
# otherwise uses otherstuf() unchanged
Run Code Online (Sandbox Code Playgroud)
这个问题是当模拟版本加载到没有win32com的环境中时,import win32com.client语句抛出.
我的问题是,限制该导入应用的正确方法是什么?
将导入嵌入到每个方法中,重复执行:
def local_instance(self):
import win32com.client
res = win32com.client.Dispatch('Foo.Bar')
def res_attrib(self):
import win32com.client
return win32com.client.Dispatch('Foo.Bar').Attribute
Run Code Online (Sandbox Code Playgroud)将导入和def嵌套在try块中,如果用户尝试在Windows环境中运行basic但是没有安装win32com,它将会奇怪地失败:
try:
import win32com.client
def local_instance(self):
res = win32com.client.Dispatch('Foo.Bar')
def res_attrib(self):
return win32com.client.Dispatch('Foo.Bar').Attribute
except:
# alternate or no defs
Run Code Online (Sandbox Code Playgroud)或其他?
嵌套导入和def在try块内,
这是大多数人使用的标准方法.
在任何类定义之外执行此操作.与您的普通进口处于最顶层.只有一次.
在模块中之后出现的任何类定义中使用这两个函数.
try:
import win32com.client
def local_instance():
res = win32com.client.Dispatch('Foo.Bar')
def res_attrib():
return win32com.client.Dispatch('Foo.Bar').Attribute
except ImportError, why:
# alternate or no defs
Run Code Online (Sandbox Code Playgroud)
如果用户试图在Windows环境中运行基本但是没有安装win32com,那么它将会奇怪地失败:
这根本不是真的.
首先,您可以检查why变量.
其次,您可以检查os.name或platform.uname()查看这是否是Win32并except根据操作系统更改块.