考虑下面的Python代码:

import os
print os.getcwd()

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

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

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

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


当前回答

试试这个:

def get_script_path(for_file = None):
    path = os.path.dirname(os.path.realpath(sys.argv[0] or 'something'))
    return path if not for_file else os.path.join(path, for_file)

其他回答

使用os.path.abspath(”)

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

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

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

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

import os
print(os.path.dirname(os.path.realpath(__file__)))

试试这个:

def get_script_path(for_file = None):
    path = os.path.dirname(os.path.realpath(sys.argv[0] or 'something'))
    return path if not for_file else os.path.join(path, for_file)

我使用:

import os
import sys

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

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