考虑下面的Python代码:
import os
print os.getcwd()
我使用os.getcwd()来获取脚本文件的目录位置。当我从命令行运行脚本时,它会给我正确的路径,而当我从Django视图中由代码运行的脚本运行它时,它会打印/。
如何从Django视图运行的脚本中获取脚本的路径?
更新:
总结到目前为止的答案- os.getcwd()和os.path.abspath()都给出了当前工作目录,该目录可能是脚本所在的目录,也可能不是。在我的web主机设置__file__只给出文件名没有路径。
在Python中没有任何方法(总是)能够接收脚本驻留的路径吗?
尝试sys.path[0]。
引用Python文档:
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
来源:https://docs.python.org/library/sys.html sys.path