考虑下面的Python代码:

import os
print os.getcwd()

我使用os.getcwd()来获取脚本文件的目录位置。当我从命令行运行脚本时,它会给我正确的路径,而当我从Django视图中由代码运行的脚本运行它时,它会打印/。

如何从Django视图运行的脚本中获取脚本的路径?

更新: 总结到目前为止的答案- os.getcwd()和os.path.abspath()都给出了当前工作目录,该目录可能是脚本所在的目录,也可能不是。在我的web主机设置__file__只给出文件名没有路径。

在Python中没有任何方法(总是)能够接收脚本驻留的路径吗?


当前回答

这是一个相当老的线程,但当我试图将文件保存到脚本所在的当前目录时,从cron作业运行python脚本时,一直有这个问题。Getcwd()和许多其他路径会显示您的主目录。

来获取我使用的脚本的绝对路径

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

其他回答

我使用:

import os
import sys

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

正如aiham在评论中指出的那样,您可以在模块中定义这个函数,并在不同的脚本中使用它。

import os,sys
# Store current working directory
pwd = os.path.dirname(__file__)
# Append current directory to the python path
sys.path.append(pwd)

你需要在__file__上调用os.path.realpath,这样当__file__是一个没有路径的文件名时,你仍然会得到dir路径:

import os
print(os.path.dirname(os.path.realpath(__file__)))
import os
exec_filepath = os.path.realpath(__file__)
exec_dirpath = exec_filepath[0:len(exec_filepath)-len(os.path.basename(__file__))]

这是我最后得到的结果。这适用于我,如果我导入我的脚本在解释器,也如果我执行它作为一个脚本:

import os
import sys

# Returns the directory the current script (or interpreter) is running in
def get_script_directory():
    path = os.path.realpath(sys.argv[0])
    if os.path.isdir(path):
        return path
    else:
        return os.path.dirname(path)