How can I tell which module/script has just run this script in Python?
Problem Description:
I have a module called detector.py
, and I want to import the module Vimba
into it only if detector.py
is being imported by experiment.py
. Is this importer-specific conditional importing possible?
If I import this module (detector.py
) into a different module, say test.py
, I don’t want to try to import Vimba
.
I’ve tried checking __name__
to see if it tells me who my importer is, but I only get the general module path of this module project.detection.detector
.
Solution – 1
You can use sys.modules
to check if a module has been imported.
import sys
if 'experiment' in sys.modules:
import Vimba