Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - get the full file path a function was called from?

Tags:

python

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 did

from mymodule import foo
foo()

And then ran python3 test.py in the terminal, it should print the full file path of test.py

like image 299
13steinj Avatar asked Dec 19 '15 05:12

13steinj


People also ask

How do I get the full file path in Python?

To get an absolute path in Python you use the os. path. abspath library. Insert your file name and it will return the full path relative from the working directory including the file.

How do you find the path of a function in Python?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

What is __ file __ in Python?

__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.


1 Answers

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
like image 138
Remi Crystal Avatar answered Nov 14 '22 23:11

Remi Crystal