Get name of current script in Python

前端 未结 18 2398
北荒
北荒 2020-11-28 00:54

I\'m trying to get the name of the Python script that is currently running.

I have a script called foo.py and I\'d like to do something like this in ord

18条回答
  •  臣服心动
    2020-11-28 01:17

    As of Python 3.5 you can simply do:

    from pathlib import Path
    Path(__file__).stem
    

    See more here: https://docs.python.org/3.5/library/pathlib.html#pathlib.PurePath.stem

    For example, I have a file under my user directory named test.py with this inside:

    from pathlib import Path
    
    print(Path(__file__).stem)
    print(__file__)
    

    running this outputs:

    >>> python3.6 test.py
    test
    test.py
    

提交回复
热议问题