0

I ran into some trouble with modules lately. I'm having a hard timefiguring out how I can get the file that has imported the module. basically:

import sys
imported = sys.get_modules_that_have_imported_this_script()

#and then the rest of the code

to be more specific. modules run when you import them right? so is there a way to get what program the module is running from? (preferably the path or file name)

edit: i want the file name so I can use the inspect module to get source code

edit2: I don't want to get the source of the module. I want to find the main program from a module imported within it

edit3: maybe this will help https://pasteboard.co/OMO6tQoTKALI.png

hacker man
  • 1
  • 1
  • 2
  • `sys.argv[0]`? More information about the use case would help (i.e. what do you need to do with this information?) – Samwise May 09 '22 at 23:32
  • 1
    Have you seen these? https://stackoverflow.com/questions/6409935/where-is-the-sys-module-in-python-source-code – Mohamad Ghaith Alzin May 10 '22 at 00:34
  • https://stackoverflow.com/questions/8608587/finding-the-source-code-for-built-in-python-functions – Mohamad Ghaith Alzin May 10 '22 at 00:36
  • good answers but none have _quite_ answered my question. perhaps I should explain it better? – hacker man May 10 '22 at 00:41
  • Hi thanks for drawing a picture but no need :-D I think the boldfaced text makes it pretty clear. – alexis May 10 '22 at 00:55
  • Interesting puzzle, but somehow it's an unusual request. Like @samwise wrote, please explain what you plan to do with this information (what do you plan to do with the source code of your main script), so we can understand if perhaps there is a better way to get there. – alexis May 10 '22 at 00:57
  • To expand a little: what precisely do you mean by "the main program"? The absolute path to the script on disk? The symbolic name of the module? The AST node corresponding to the scope where the `import` happened? If you explain what you envision doing *after* you find "the main program" it would be easier to figure out what you mean by that phrase. – Samwise May 10 '22 at 01:14
  • thanks for the help! I never would have thought of that :) – hacker man May 10 '22 at 01:27

1 Answers1

0

I found the answer in here How to get filename of the __main__ module in Python?

If you have two files main.py and module.py, this is how you can find the path of main.py from module.py

main.py

import module

module.function()

module.py

import __main__

main_filename = __main__.__file__

def function():
...
Edward
  • 150
  • 1
  • 4