Get name of current script in Python

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

    You can do this without importing os or other libs.

    If you want to get the path of current python script, use: __file__

    If you want to get only the filename without .py extension, use this:

    __file__.rsplit("/", 1)[1].split('.')[0]
    
    0 讨论(0)
  • 2020-11-28 01:03

    My fast dirty solution:

    __file__.split('/')[-1:][0]
    
    0 讨论(0)
  • 2020-11-28 01:04

    os.path.abspath(__file__) will give you an absolute path (relpath() available as well).

    sys.argv[-1] will give you a relative path.

    0 讨论(0)
  • 2020-11-28 01:05

    Note that __file__ will give the file where this code resides, which can be imported and different from the main file being interpreted. To get the main file, the special __main__ module can be used:

    import __main__ as main
    print(main.__file__)
    

    Note that __main__.__file__ works in Python 2.7 but not in 3.2, so use the import-as syntax as above to make it portable.

    0 讨论(0)
  • 2020-11-28 01:07

    If you're doing an unusual import (e.g., it's an options file), try:

    import inspect
    print (inspect.getfile(inspect.currentframe()))
    

    Note that this will return the absolute path to the file.

    0 讨论(0)
  • 2020-11-28 01:08

    For modern Python versions (3.4+), Path(__file__).name should be more idiomatic. Also, Path(__file__).stem gives you the script name without the .py extension.

    0 讨论(0)
提交回复
热议问题