[英]From *folder_name* import *variable* Python 3.4.2
档案设定:
...\Project_Folder ...\Project_Folder\Project.py ...\Project_folder\Script\TestScript.py
我试图根据用户输入从文件夹Script中导入Project.py导入模块。
Python版本:3.4.2
理想情况下,脚本应类似于
q = str(input("Input: "))
from Script import q
但是,使用import时,python无法将q识别为变量。
我尝试使用importlib ,但是我不知道如何从上述Script文件夹中导入。
import importlib
q = str(input("Input: "))
module = importlib.import_module(q, package=None)
我不确定在哪里实现文件路径。
重复我最初在如何导入给定完整路径的模块中发布的答案的步骤? 因为这是Python 3.4的特定问题:
Python 3.4的这一领域似乎很难理解,主要是因为文档没有给出很好的示例! 这是我尝试使用不建议使用的模块。 给定.py文件的路径,它将导入一个模块。 我正在使用它在运行时加载“插件”。
def import_module_from_file(full_path_to_module):
"""
Import a module given the full path/filename of the .py file
Python 3.4
"""
module = None
try:
# Get module name and path from full path
module_dir, module_file = os.path.split(full_path_to_module)
module_name, module_ext = os.path.splitext(module_file)
# Get module "spec" from filename
spec = importlib.util.spec_from_file_location(module_name,full_path_to_module)
module = spec.loader.load_module()
except Exception as ec:
# Simple error printing
# Insert "sophisticated" stuff here
print(ec)
finally:
return module
# load module dynamically
path = "<enter your path here>"
module = import_module_from_file(path)
# Now use the module
# e.g. module.myFunction()
我通过将整个导入行定义为字符串,使用q格式化字符串然后使用exec命令来完成此操作:
imp = 'from Script import %s' %q
exec imp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.