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

后端 未结 29 2221
你的背包
你的背包 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:51

    This should work:

    import os,sys
    filename=os.path.basename(os.path.realpath(sys.argv[0]))
    dirname=os.path.dirname(os.path.realpath(sys.argv[0]))
    
    0 讨论(0)
  • 2020-11-22 06:51

    Here is what I use so I can throw my code anywhere without issue. __name__ is always defined, but __file__ is only defined when the code is run as a file (e.g. not in IDLE/iPython).

    if '__file__' in globals():
        self_name = globals()['__file__']
    elif '__file__' in locals():
        self_name = locals()['__file__']
    else:
        self_name = __name__
    

    Alternatively, this can be written as:

    self_name = globals().get('__file__', locals().get('__file__', __name__))
    
    0 讨论(0)
  • 2020-11-22 06:52

    The __file__ attribute works for both the file containing the main execution code as well as imported modules.

    See https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__

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

    as others have said. You may also want to use os.path.realpath to eliminate symlinks:

    import os
    
    os.path.realpath(__file__)
    
    0 讨论(0)
  • 2020-11-22 06:54

    Try this,

    import os
    os.path.dirname(os.path.realpath(__file__))
    
    0 讨论(0)
  • 2020-11-22 06:56

    It's not entirely clear what you mean by "the filepath of the file that is currently running within the process". sys.argv[0] usually contains the location of the script that was invoked by the Python interpreter. Check the sys documentation for more details.

    As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to

    the file from which the module was loaded, if it was loaded from a file

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