问题
I use numpy and scipy for data analysis. I want to write a code inside a function that I define so that when the function is called it check if, for example, numpy is imported and if it is not imported, then it should import it.
How can I check if any module such as numpy imported?
回答1:
The import
statement is idempotent - it already checks whether the module has been loaded. Using import module
in your function already does what you want:
def my_func():
import numpy # load numpy if not available
# use numpy
This works for all kinds of imports, including submodules, relative imports and aliasing of members.
def my_other_func():
# load skimage, skimage.morphology, and
# skimage.morphology.watershed if they are unimported modules
from skimage.morphology import watershed
During import, the module name is looked up in
sys.modules
and if present, the associated value is the module satisfying the import, and the process completes. [...][The Python Language Reference: the import system]
回答2:
You can use sys.modules in the sys
module for this:
>>> import sys
>>> import numpy
>>> 'numpy' in sys.modules
True
So your function could be:
def is_imported(module):
return module in sys.modules
From the comments, you also wanted to return True
if you'd used
from skimage.morphology import watershed
You can check if a function is in the current namespace by using dir()
>>> 'watershed' in dir()
False
>>> from skimage.morphology import watershed
>>> 'watershed' in dir()
True
To import a module using a string, you can use importlib.import_module():
>>> import importlib
>>> importlib.import_module('numpy')
来源:https://stackoverflow.com/questions/59271953/how-to-check-if-a-module-is-imported