How to get the current running module path/name

前端 未结 8 1970
不知归路
不知归路 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 19:59

    One liner But OS dependent

    it does not work in interpreter! since file is meaningless there in the interpreter and is not defined.

    does not require os module to be imported.

    modulename=__file__.split("\\")[-1].split('.')[0]
    

    Explanation: X:\apple\pythonabc.py | will output pythonabc.py

    select the last element after splitting with slashes, then select the first element by splitting it with dot '.'. because first step gives module.py, second step gives 'module' only. __file__ is a unique variable and returns the filepath of current module.

    Comment any flaws or has any other pitfalls.

提交回复
热议问题