Last active
December 16, 2015 11:24
-
-
Save zhanglongqi/50298edad914ef01e5cf to your computer and use it in GitHub Desktop.
how to import module from relative path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, sys, inspect | |
# realpath() will make your script run, even if you symlink it :) | |
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])) | |
if cmd_folder not in sys.path: | |
sys.path.insert(0, cmd_folder) | |
# use this if you want to include modules from a subfolder | |
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder"))) | |
if cmd_subfolder not in sys.path: | |
sys.path.insert(0, cmd_subfolder) | |
# Info: | |
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!! | |
# __file__ fails if script is called in different ways on Windows | |
# __file__ fails if someone does os.chdir() before | |
# sys.argv[0] also fails because it doesn't not always contains the path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This answer comes from stackoverflow