考虑以下 Python 代码:
import os
print os.getcwd()
我用来os.getcwd()
获取脚本文件的目录位置。当我从命令行运行脚本时,它会给我正确的路径,而当我从 Django 视图中的代码运行的脚本运行它时,它会打印/
。
如何从 Django 视图运行的脚本中获取脚本的路径?
更新:
总结到目前为止的答案 -os.getcwd()
两者os.path.abspath()
都给出了当前工作目录,该目录可能是也可能不是脚本所在的目录。在我的 Web 主机设置中,__file__
只提供文件名,没有路径。
Python 中是否没有任何方法可以(始终)接收脚本所在的路径?
为了可靠地获取 Python 中脚本文件的路径(它所在的位置),可以使用__file__
属性__file__
多变的os.path.abspath()
和`os.path.dirname()
。
您可以使用以下方法始终获取脚本文件的目录,即使它在 Django 中执行
import os
# Get the absolute path to the script file (__file__ gives the script's filename or relative path)
script_directory = os.path.dirname(os.path.abspath(__file__))
script_directory = os.path.dirname(os.path.abspath(__file
script_directory = os.path.dirname(os.path.abspath(__
script_directory = os.path.dirname(os.path
script_directory = os.path.dirname
script_directory = os
script_directory =
script_directory
print(script_directory)
__file__
给出os.path.abspath(__file__)
丙os.path.dirname()
提取物这将为你提供脚本所在的目录,即使你
os.getcwd()
将给予/
),/
当运行os.path.dirname(os.path.abspath(__file__))
这种方法应该在不同的环境(命令行、Django 视图、