我可以检查 Python 中的模块,例如:
try:
import some_module
except ImportError:
print "No some_module!"
但我不想使用 try/except。有没有办法做到这一点?(它应该适用于 Python 2.5.x。)
注意:不使用 try/except 的原因是任意的,只是因为我想知道是否有一种方法可以在不使用异常的情况下对其进行测试。
我可以检查 Python 中的模块,例如:
try:
import some_module
except ImportError:
print "No some_module!"
但我不想使用 try/except。有没有办法做到这一点?(它应该适用于 Python 2.5.x。)
注意:不使用 try/except 的原因是任意的,只是因为我想知道是否有一种方法可以在不使用异常的情况下对其进行测试。
执行请求需要技巧(raise
事实上,一个语句是不可避免的,因为它是 PEP 302 中指定的唯一一种方式,用于导入挂钩说“我不处理此路径项”!),但以下将避免任何try
/ except
:
import sys
sentinel = object()
class FakeLoader(object):
def find_module(self, fullname, path=None):
return self
def load_module(*_):
return sentinel
def fakeHook(apath):
if apath == 'GIVINGUP!!!':
return FakeLoader()
raise ImportError
sys.path.append('GIVINGUP!!!')
sys.path_hooks.append(fakeHook)
def isModuleOK(modulename):
result = __import__(modulename)
return result is not sentinel
print 'sys', isModuleOK('sys')
print 'Cookie', isModuleOK('Cookie')
print 'nonexistent', isModuleOK('nonexistent')
这打印:
sys True
Cookie True
nonexistent False
Of course, these would be absurd lengths to go to in real life for the pointless purpose of avoiding a perfectly normal try
/except
, but they seem to satisfy the request as posed (and can hopefully prompt Python-wizards wannabes to start their own research -- finding out exactly how and why all of this code does work as required is in fact instructive, which is why for once I'm not offering detailed explanations and URLs;-).
您可以在此处阅读有关 Python 如何定位和导入模块的信息。如果你愿意,你可以在 python 中复制这个逻辑,搜索 sys.modules、sys.meta_path 和 sys.path 来寻找所需的模块。
但是,我想,在不使用异常处理的情况下预测它是否会成功解析(考虑编译的二进制模块)将非常困难!
所有导入模块的方法在调用时都会引发异常。您可以先尝试自己在文件系统中搜索文件,但有很多事情需要考虑。
不知道为什么你不想使用try
/except
虽然。这是最好的解决方案,比我提供的要好得多。try
也许您应该首先澄清这一点,因为您可能有不使用/的无效理由except
。
sys.modules 字典似乎包含您需要的信息。