如何使用Python找到脚本的目录?

2024-04-26 11:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

请考虑以下Python代码:

import os
print os.getcwd()

我用os.getcwd()get the script file's directory location。当我从命令行运行脚本时,它会给出正确的路径,而当我从Django视图中由代码运行的脚本运行脚本时,它会打印/

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

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

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


Tags: thedjango代码import路径目录脚本视图
3条回答

尝试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

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

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

我使用:

import os
import sys

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

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

相关问题 更多 >