Python: How to Find Python Interpreter Path, Script Path, from Running Script

By Xah Lee. Date: . Last updated: .

How to find the Python interpreter path from current script?

# -*- coding: utf-8 -*-
# python

import sys

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

# sample output on linux
# /usr/bin/python

# sample output on Windows
# C:\Python27\python.exe

27.1. sys — System-specific parameters and functions — Python v2.7.6 documentation #sys.executable

How to find the path of current running script?

get it from the __file__ attribute.

# -*- coding: utf-8 -*-
# python

import os

# path of current script
print os.path.realpath(__file__) # sample output  /home/h3/my-print-path.py

10.1. os.path — Common pathname manipulations — Python v2.7.6 documentation #os.path.realpath

How to find a module's path?

# -*- coding: utf-8 -*-
# python

import os
print os.__file__               # sample output C:\Python27\lib\os.pyc