How to get the current running module path/name

前端 未结 8 1987
不知归路
不知归路 2021-02-03 19:19

I\'ve searched and this seems to be a simple question without a simple answer.

I have the file a/b/c.py which would be called with python -m a.b.c

8条回答
  •  爱一瞬间的悲伤
    2021-02-03 20:13

    Number of options are there to get the path/name of the current module.

    First be familiar with the use of __file__ in Python, Click here to see the usage.

    It holds the name of currently loaded module.

    Check/Try the following code, it will work on both Python2 & Python3.

    » module_names.py

    import os
    
    print (__file__)
    print (os.path.abspath(__file__))
    print (os.path.realpath(__file__))
    

    Output on MAC OS X:

    MacBook-Pro-2:practice admin$ python module_names.py 
    module_names.py
    /Users/admin/projects/Python/python-the-snake/practice/module_names.py
    /Users/admin/projects/Python/python-the-snake/practice/module_names.py
    

    So here we got the name of current module name and its absolute path.

提交回复
热议问题