How to properly determine current script directory

2018-12-31 08:48发布

I would like to see what is best way to determine current script directory in python?

I discovered that two to the many ways of calling python code, it is hard to find a good solution.

Here are some problems:

  • __file__ is not defined if the script is executed with exec, execfile
  • __module__ is defined only in modules

Use cases:

  • ./myfile.py
  • python myfile.py
  • ./somedir/myfile.py
  • python somedir/myfile.py
  • execfile('myfile.py') (from another script, that can be located in another directory and that can have another current directory.

I know that there is no perfect solution, because in some cases but I'm looking for the best approach that solved most of the cases.

The most used approach is os.path.dirname(os.path.abspath(__file__)) but this really doesn't work if you execute the script from another one with exec().

Warning

Any solution that uses current directory will fail, this can be different based on the way the script is called or it can be changed inside the running script.

13条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 09:36
import os
import sys

def get_script_path():
    return os.path.dirname(os.path.realpath(sys.argv[0]))


my_script_dir = get_script_path()
print my_script_dir

This gives you the directory of the script at the top of the stack (i.e. the one being executed - not Python's, which is usually the first executed, returning C:/)

查看更多
登录 后发表回答