在from import语句中的python函数中使用输入
我想使用文件“a.py”中函数中的输入(字符串)指向另一个python代码文件“b.py”。在b.py代码中,我有一些函数,我想使用 我试过: b、 皮耶 (b.py位于a.py的子文件夹中,名为.app.dashapp1) 和a.py:在from import语句中的python函数中使用输入,python,function,module,python-import,importerror,Python,Function,Module,Python Import,Importerror,我想使用文件“a.py”中函数中的输入(字符串)指向另一个python代码文件“b.py”。在b.py代码中,我有一些函数,我想使用 我试过: b、 皮耶 (b.py位于a.py的子文件夹中,名为.app.dashapp1) 和a.py: def function(func_name): name = "app.dashapp1." + func_name __import__(name) function1(2, 4) return function("b")
def function(func_name):
name = "app.dashapp1." + func_name
__import__(name)
function1(2, 4)
return
function("b")
当我运行a.py时,我最终得到错误消息:
“名称错误:未定义名称‘function1’”
:(
我来自matlab/R,对Python(尽管我很喜欢)和这个论坛是个新手
谢谢!您忘记将名称
function1
绑定到函数
def function(func_name):
name = "app.dashapp1." + func_name
function1 = __import__(name).function1
function1(2, 4)
return
function("a")
它将使用importlib.import\u模块
而不是\u导入
:
a.py
:
导入导入库
def func(名称):
module_str=“dashapp1.”+name#获取module str
module=importlib.import_module(module_str)#从str导入模块
f=getattr(模块,“函数”)#在模块中获取函数“函数”
f(1,2)#执行模块中的函数“function”
func(“b”)
dashapp1/b.py
:
def功能(a、b):
打印(“{a}-{b}”。格式(a=a,b=b))
输出:
$ python3.7 a.py
1 - 2
非常感谢您的快速回答!我现在得到了这个错误,使用建议的代码:>AttributeError:module'app'没有属性'function1'函数假设模块app.dashapp1.有一个function1,如果您想使用模块b,您应该用
name=“app.dashapp1.”+func\u name
替换为name=“b”
$ python3.7 a.py
1 - 2