Python: Find Script Path

By Xah Lee. Date: . Last updated: .

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

# python 3

import sys

# path of the python interpreter
print(sys.executable)

# /Users/xah/anaconda3/bin/python3

Find the path of current running script

Path of current running stript is stored in the attribute:

__file__

# python 3

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

module_name.__file__

# python 3

import os
print(os.__file__)

# /Users/xah/anaconda3/lib/python3.7/os.py

Python: Paths Topic

Python

Regex

Text Processing

Web

Misc