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

后端 未结 12 1811
情深已故
情深已故 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:48

    os.path.dirname(os.path.abspath(__file__))
    

    is indeed the best you're going to get.

    It's unusual to be executing a script with exec/execfile; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting __file__ in the globals you pass to the script so it can read that filename.

    There's no other way to get the filename in execed code: as you note, the CWD may be in a completely different place.

提交回复
热议问题