我有一长串可能需要导入的文件。我将只需要他们中的一个,他们都有相同的接口。(选择支付网关处理支付)
假设我有一个表示所有网关文件名称的字典。
即
gateways = {
'1' : 'authorize',
'2' : 'paysimple',
'3' : 'braintreepayments',
'4' : 'etc',
}我根据数据库中的信息知道了这本词典的关键字。因此,如果我收到一个网关值为1的支付处理请求,我知道它需要由Authorize.net处理。A 2将由Pay Simple处理。等。
我希望能够创建一个import语句,它是用我知道的信息构建的,而不是一个可怕的elif语句列表。
考虑下面这个简单的方法:
# For the purposes of this example assume payment_gateway is defined
# elsewhere and represents the key to the dictionary
gateway_file = gateways.get(payment_gateway)
import_str = "from gateway_interface.%s import process" % gateway_file
gogo(import_str)其中,gogo是一种使import语句实际导入的方法。
这样的事情有可能吗?
发布于 2012-07-10 08:34:11
最简单
process = __import__('gateway_interface.'+gateway_file,fromlist=['foo']).process编辑列表: fromlist中的'foo‘可以是任何东西,只要fromlist不是一个空列表。这一点奇怪之处在Why does Python's __import__ require fromlist?中得到了解释。
我还不得不编辑,因为在我的第一篇文章中,__import__没有像Python's __import__ doesn't work as expected中进一步描述的那样工作。
如果你有python 2.7
import importlib
process = importlib.import_module('gateway_interface.'+gateway_file).process非常酷的是使用package_tools (例如from pkg_resources import iter_entry_points)
这可以为您提供一个解决方案来找到正确的函数,即使它们位于奇怪的包中,而不是gateway_interface下。如果它们都在一个地方,并且你不需要过度杀伤力的音节点,那么……是的,就是__import__
发布于 2012-07-10 07:23:04
看看imp模块,它允许您访问import语句的内部结构,或者__import__方法本身-我认为这两个模块都应该允许您实现您所描述的内容。
发布于 2012-07-10 08:25:26
内置的__import__方法应该可以工作:
process = __import__(gateways.get(payment_gateway)).processhttps://stackoverflow.com/questions/11404617
复制相似问题