如何使用字符串变量作为位置来访问模块?

How do I access a module using a string variable as a location?

我有一个字符串变量x,想用input调用子文件夹下的模块,如下图。如何将此字符串用作路径的一部分?

x = input()

from subfolder.x import y

我的代码是 运行 来自父文件夹 'main.py' 并使用以下行:

os.chdir(os.path.dirname(os.path.abspath(__file__)))

设置文件路径。

根据 Python 文档,以下是 import 语句如何搜索要导入的正确模块或包:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.pathsys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory.

来源:Python2 和 3

因此您可以使用 sys.path.append 将位置附加到路径,但是一旦您关闭 Python,sys.path 将被设置回默认值。
或者您可以通过添加

将所需位置永久添加到 PYTHONPATH
export PYTHONPATH="${PYTHONPATH}:/my/other/path"

在适用于您正在使用的任何 shell 的启动脚本中(例如,.bashrc 用于 bash)

如果需要动态导入,请查看importlib.import_module考虑以下简单示例

import importlib
modulename = "html"
submodulename = "entities"
what = "html5"
module = importlib.import_module(modulename + "." + submodulename)
thing = getattr(module,what)
print(thing["gt;"])  # >