标准库清楚地记录了如何直接导入源文件(给定源文件的绝对文件路径),但如果源文件使用隐式同级导入,则此方法不起作用,如下例所示.
如果这个例子适用于隐式兄弟导入的存在?
我已经签出这个和这个其他的话题#1的问题,但他们并没有解决隐同级进口内用手导入的文件.
这是一个说明性的例子
目录结构:
root/
- directory/
- app.py
- folder/
- implicit_sibling_import.py
- lib.py
Run Code Online (Sandbox Code Playgroud)
app.py:
import os
import importlib.util
# construct absolute paths
root = os.path.abspath(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
isi_path = os.path.join(root, 'folder', 'implicit_sibling_import.py')
def path_import(absolute_path):
'''implementation taken from https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly'''
spec = importlib.util.spec_from_file_location(absolute_path, absolute_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
isi = path_import(isi_path)
print(isi.hello_wrapper())
Run Code Online (Sandbox Code Playgroud)
lib.py:
def hello():
return 'world'
Run Code Online (Sandbox Code Playgroud)
implicit_sibling_import.py:
import lib # this is the …Run Code Online (Sandbox Code Playgroud) 给出模块名称列表(例如mymods = ['numpy','scipy',...])如何检查模块是否可用?
我试过以下但是不正确:
for module_name in mymods:
try:
import module_name
except ImportError:
print "Module %s not found." %(module_name)
Run Code Online (Sandbox Code Playgroud)
谢谢.