How do you properly determine the current script directory in Python?

后端 未结 12 1652
情深已故
情深已故 2020-11-22 02:30

I would like to see what is the best way to determine the current script directory in Python.

I discovered that, due to the many ways of calling Python code, it is ha

12条回答
  •  终归单人心
    2020-11-22 02:50

    Here is a partial solution, still better than all published ones so far.

    import sys, os, os.path, inspect
    
    #os.chdir("..")
    
    if '__file__' not in locals():
        __file__ = inspect.getframeinfo(inspect.currentframe())[0]
    
    print os.path.dirname(os.path.abspath(__file__))
    

    Now this works will all calls but if someone use chdir() to change the current directory, this will also fail.

    Notes:

    • sys.argv[0] is not going to work, will return -c if you execute the script with python -c "execfile('path-tester.py')"
    • I published a complete test at https://gist.github.com/1385555 and you are welcome to improve it.

提交回复
热议问题