Trying to provide a dirty workaround for my problem described here, I want to retrieve the name of the currently executed module by reading the command line.
But it looks like a higher power tries to prevent me from achieving my goal..
When I start my_module
via
python3 -m my_module
sys.argv
happens to be ['-m']
Is this correct? Shouldn't it be either []
, ['my_module']
or even ['-m', 'my_module']
?
What can I do here to get 'my_module'?
Note: I know, I can always access __name__
or __package__
, but I need to find the name of the module from within a module different from the executed module itself.
How to reproduce:
I have the following directory structure:
my_module/
├── __init__.py
└── __main__.py
With __main__
being empty and __init__.py
only containing
import sys
print(sys.argv)
Output:
$ python3 -m my_module
['-m']
Workaround:
In case you need something similar, here is how I did it in the end:
def get_module_name() -> str:
from psutil import Process
from os import getpid
_cmdline = Process(getpid()).cmdline
try:
return _cmdline[_cmdline.index('-m') + 1]
except ValueError:
return None