Skip to content Skip to sidebar Skip to footer

Python - Get The Full File Path A Function Was Called From?

Given a module mymodule.py; and in it def foo(): X = # file path where foo was called from print(X) How would I do what's described in the comment? Ie, if in test.py I di

Solution 1:

You could use sys.argv[0] to get the main file 's name, then you could use os.path.realpath() to get the full path of it:

import os
import sys

def foo():
    X = os.path.realpath(sys.argv[0])
    print(X)

Demo:

kevin@Arch ~> python test.py 
/home/kevin/test.py

Solution 2:

You can use os.path.realpath to get full path to curently executing file:

import os

def func():
  full_path = os.path.realpath(__file__)
  print(full_path)

if (__name__ == "__main__"):
  func()

Post a Comment for "Python - Get The Full File Path A Function Was Called From?"