Python: Find Script Path
Here's how to find python executable path, current script path, module path, from a running script. Printing path from a running program is important, because if you call it in shell, it may be using a different environment.
Find the Python interpreter path from current script
Python interpreter path is stored in:
sys.executable
import sys print(sys.version) # 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] # path of the python interpreter print(sys.executable) # C:\Python39\python.exe
Find the path of current running script
Path of current running script is stored in the attribute:
__file__
import os # path of current script print(os.path.realpath(__file__)) # /Users/xah/web/xahlee_info/python/xxtemp.20190319.288.py3
Find a module's path
Module's path is stored at variable
moduleName.__file__
import os print(os.__file__) # /Users/xah/anaconda3/lib/python3.7/os.py