as a literal answer to the question 'Python Import from parent directory':
to import 'mymodule' that is in the parent directory of your current module:
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir)
import mymodule
edit
Unfortunately, the __file__
attribute is not always set.
A more secure way to get the parentdir is through the inspect module:
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…