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

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

    If you really want to cover the case that a script is called via execfile(...), you can use the inspect module to deduce the filename (including the path). As far as I am aware, this will work for all cases you listed:

    filename = inspect.getframeinfo(inspect.currentframe()).filename
    path = os.path.dirname(os.path.abspath(filename))
    

提交回复
热议问题