Wednesday, August 24, 2022

[FIXED] How do I get the file path of python script within loaded module?

Issue

I wrote a module module.py that I import in various scripts. The module has a function that needs the file path of the script main.py that it was imported by and do something with it. How do I get this file path?

module.py

def main_file_path():
    print(way_to_acces_main_file_path)

is imported in

main.py

import module
module.main_file_path()

Running main.py should print the file path of main.py


Solution

The system argv always has the program name as the first element. This should work most of the time:

import sys
import os

path = os.path.abspath(sys.argv[0])
print(path)


Answered By - Keith
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.