Get name of current script in Python

前端 未结 18 2395
北荒
北荒 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:12

    Note: If you are using Python 3+, then you should use the print() function instead

    Assuming that the filename is foo.py, the below snippet

    import sys
    print sys.argv[0][:-3]
    

    or

    import sys
    print sys.argv[0][::-1][3:][::-1]
    

    As for other extentions with more characters, for example the filename foo.pypy

    import sys
    print sys.argv[0].split('.')[0]
    

    If you want to extract from an absolute path

    import sys
    print sys.argv[0].split('/')[-1].split('.')[0]
    

    will output foo

提交回复
热议问题