1

There are python files a.py and b.py. And b.py is imported in a.py by import b. How to get the absolute path of a.py in b.py when a.py runs?

DennisLi
  • 3,915
  • 6
  • 30
  • 66
Hank Chow
  • 446
  • 4
  • 13
  • 3
    Possible duplicate of [How to retrieve a module's path?](https://stackoverflow.com/questions/247770/how-to-retrieve-a-modules-path) – bhansa Jul 04 '19 at 09:08

1 Answers1

0

b.py

import os
import traceback


try: assert 0
except:
    st = traceback.format_stack()
     # format of st --> ['  File "filename", line 1, in <module>\n    import b\n', ... ... ]
    relative_p = st[0].split(',')[0].split(' ')[-1].split('"')[1]
    abs_path = os.path.abspath(relative_p)
    print(abs_path)
    # prints the importer's path, else if no importer, then itself's abs path

# rest of program goes here ...
Community
  • 1
  • 1
Vicrobot
  • 3,795
  • 1
  • 17
  • 31