Python导入包含在变量中的文件名的函数 [英] Python importing a function with file's name contained in a variable
问题描述
您好我的主脚本在同一个文件夹中有一个名为'actions'的目录,在这个文件夹中有几个脚本可以在任何时候由主脚本使用。我正处于一个名为VAR的变量中以字符串形式出现的脚本名称(为了示例)。我希望能够使用变量导入此文件。
Hi I have a directory in the same folder as my main script called 'actions' in this folder there are several scripts that may be used at any time by the main script. I am at the point where I have the name of the script in the form of a string in a variable called VAR (for the sake of example). I would like to be able to import this file using the variable.
推荐答案
如果您的目标只是执行文件,那么您可以使用
If your aim is simply to execute the files, you can use
with open(filename) as f:
exec(compile(f.read(), filename, "exec"))
或Python 2.x函数 execfile()
。
or the Python 2.x function execfile()
.
如果您确实想使用完整导入机制导入模块,则需要 __ init __。py
在目录 actions
中,可以使用
If you actually want to import the modules using the full import machinery, you need an __init__.py
in the directory actions
, and can use something like
module = __import__("actions.foo")
导入 actions / foo.py
。
这篇关于Python导入包含在变量中的文件名的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!