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
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.
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.
__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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With