简体   繁体   English

Python 文件导入使用字符串

[英]Python file imports using a string

I am trying to import a function from another python file in a different directory but only have the function name in string form.我正在尝试从另一个目录中的另一个 python 文件导入 function,但只有字符串形式的 function 名称。 I have tried using import lib as follows:我尝试使用 import lib 如下:

sys.path.insert(1, file_path) # Works fine
import file # Works fine
run_function = importlib.import_module("file.function"+str(loop)) # Error occurs here

But when I try this I get the error message: ModuleNotFoundError: No module named 'file.function1'; 'file' is not a package但是当我尝试这个时,我收到错误消息: ModuleNotFoundError: No module named 'file.function1'; 'file' is not a package ModuleNotFoundError: No module named 'file.function1'; 'file' is not a package

I have also tried doing:我也尝试过这样做:

from file import *
eval("function{loop}()")

But with this method I recieve the error message: SyntaxError: import * only allowed at module level但是使用这种方法,我收到错误消息: SyntaxError: import * only allowed at module level

I am not sure exactly how to fix the issue or whether there would be a better way of doing this.我不确定如何解决这个问题,或者是否有更好的方法来解决这个问题。 I am open to suggestions.我愿意接受建议。 Thanks!谢谢!

You don't import functions.你不导入函数。 You have successfully imported the module, which includes the function, so all you have to do is get it你已经成功导入了模块,其中包括function,所以你要做的就是得到它

sys.path.insert(1, file_path) # Works fine
import file # Works fine
result = getattr(file, "function1")(loop)

You can import anywhere in the file (obviously importing within a function would limit the module scope to the function itself).您可以导入文件中的任何位置(显然,在 function 中导入会将模块 scope 限制为 function 本身)。

def func(x):
    for i in range(x):
        eval(f"from lib import function{i}")

    # All functions available in this scope

For extra safety, I recommend this be put into a try/catch.为了更加安全,我建议将其放入 try/catch 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM