How do I get the path and name of the file that is currently executing?

后端 未结 29 2237
你的背包
你的背包 2020-11-22 06:43

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

For example, let\'s say I have th

相关标签:
29条回答
  • 2020-11-22 06:57

    I think this is cleaner:

    import inspect
    print inspect.stack()[0][1]
    

    and gets the same information as:

    print inspect.getfile(inspect.currentframe())
    

    Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.

    print inspect.stack()[1][1]
    

    would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.

    0 讨论(0)
  • 2020-11-22 06:59

    To get directory of executing script

     print os.path.dirname( inspect.getfile(inspect.currentframe()))
    
    0 讨论(0)
  • 2020-11-22 06:59

    if you want just the filename without ./ or .py you can try this

    filename = testscript.py
    file_name = __file__[2:-3]
    

    file_name will print testscript you can generate whatever you want by changing the index inside []

    0 讨论(0)
  • 2020-11-22 07:00
    import os
    print os.path.basename(__file__)
    

    this will give us the filename only. i.e. if abspath of file is c:\abcd\abc.py then 2nd line will print abc.py

    0 讨论(0)
  • 2020-11-22 07:02

    I think it's just __file__ Sounds like you may also want to checkout the inspect module.

    0 讨论(0)
  • 2020-11-22 07:02

    To keep the migration consistency across platforms (macOS/Windows/Linux), try:

    path = r'%s' % os.getcwd().replace('\\','/')

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