gpt4 book ai didi

python - 如何在Python中以编程方式调用函数并以编程方式指定模块?

转载 作者:行者123 更新时间:2023-12-02 09:44:43 25 4
gpt4 key购买 nike

我不能使用这个

import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()

因为模块名称是硬编码的,我无法使用它

module = __import__('foo')
func = getattr(module, 'bar')
func()

因为模块是嵌套的。

我试过了

customer = 'jci'
module = __import__('customer.{customer_name}.gt'.format(customer_name=customer_name)) # AttributeError: module 'customer' has no attribute 'get_gt'
#module = __import__('customer.{customer_name}'.format(customer_name=customer_name), fromlist=['gt']) # AttributeError: module 'customer.jci' has no attribute 'get_gt'
#module = __import__('customer.{customer_name}.gt'.format(customer_name=customer_name), fromlist=[]) # AttributeError: module 'customer' has no attribute 'get_gt'
func = getattr(module, 'get_gt')
gt = func()

但失败并出现错误,在注释中与每个变体一起指定。

get_gt()customer/jci 目录中 gt.py 文件内的函数。每个目录里面都有空的__init__.py

以下硬编码代码有效:

import customer.jci.gt as g
gt = g.get_gt()

如何克服?

最佳答案

你想要的是importlib.import_module .

<小时/>

请注意,__import__确实处理点名称,但它返回包,而不是最后一个子包。

证明:

>>> http = __import__('http.client')
>>> http.client # the client submodule was imported
<module 'http.client' from '/usr/lib/python3.6/http/client.py'>
>>> # without specifying the .client in the name the submodule is not imported
>>> __import__('http').client
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'http' has no attribute 'client'

import_module 相反返回子模块,这是大多数人所期望的:

>>> importlib.import_module('http.client')
<module 'http.client' from '/usr/lib/python3.6/http/client.py'>

关于python - 如何在Python中以编程方式调用函数并以编程方式指定模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53745118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com