How do I get the path of the current executed file in Python?

前端 未结 13 2340
天命终不由人
天命终不由人 2020-11-22 17:06

This may seem like a newbie question, but it is not. Some common approaches don\'t work in all cases:

sys.argv[0]

This means using path = os.path.abs

相关标签:
13条回答
  • 2020-11-22 17:44

    This should do the trick in a cross-platform way (so long as you're not using the interpreter or something):

    import os, sys
    non_symbolic=os.path.realpath(sys.argv[0])
    program_filepath=os.path.join(sys.path[0], os.path.basename(non_symbolic))
    

    sys.path[0] is the directory that your calling script is in (the first place it looks for modules to be used by that script). We can take the name of the file itself off the end of sys.argv[0] (which is what I did with os.path.basename). os.path.join just sticks them together in a cross-platform way. os.path.realpath just makes sure if we get any symbolic links with different names than the script itself that we still get the real name of the script.

    I don't have a Mac; so, I haven't tested this on one. Please let me know if it works, as it seems it should. I tested this in Linux (Xubuntu) with Python 3.4. Note that many solutions for this problem don't work on Macs (since I've heard that __file__ is not present on Macs).

    Note that if your script is a symbolic link, it will give you the path of the file it links to (and not the path of the symbolic link).

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