我如何找到脚本的目录?[重复]
- 2025-02-05 13:23:00
- admin 原创
- 58
问题描述:
考虑以下 Python 代码:
import os
print os.getcwd()
我用来os.getcwd()
获取脚本文件的目录位置。当我从命令行运行脚本时,它会给我正确的路径,而当我从 Django 视图中的代码运行的脚本运行它时,它会打印/
。
如何从 Django 视图运行的脚本中获取脚本的路径?
更新:
总结到目前为止的答案 -os.getcwd()
两者os.path.abspath()
都给出了当前工作目录,该目录可能是也可能不是脚本所在的目录。在我的 Web 主机设置中,__file__
只提供文件名,没有路径。
Python 中是否没有任何方法可以(始终)接收脚本所在的路径?
解决方案 1:
您需要调用os.path.realpath
,__file__
这样当__file__
是没有路径的文件名时您仍然可以获得目录路径:
import os
print(os.path.dirname(os.path.realpath(__file__)))
解决方案 2:
尝试sys.path[0]
。
引用 Python 文档的话:
在程序启动时初始化时,此列表的第一项
path[0]
是包含用于调用 Python 解释器的脚本的目录。如果脚本目录不可用(例如,如果以交互方式调用解释器,或者如果从标准输入读取脚本),path[0]
则为空字符串,这将指示 Python 首先在当前目录中搜索模块。请注意,脚本目录插入在 的结果插入的条目之前PYTHONPATH
。
来源:https://docs.python.org/library/sys.html#sys.path
解决方案 3:
我使用:
import os
import sys
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
正如 aiham 在评论中指出的那样,您可以在模块中定义此功能并在不同的脚本中使用它。
解决方案 4:
此代码:
import os
dn = os.path.dirname(os.path.realpath(__file__))
将“dn”设置为包含当前执行脚本的目录的名称。此代码:
fn = os.path.join(dn,"vcb.init")
fp = open(fn,"r")
将“fn”设置为“script_dir/vcb.init”(以平台无关的方式)并打开该文件以供当前执行的脚本读取。
请注意,“当前正在执行的脚本”有些含糊。如果您的整个程序由 1 个脚本组成,那么这就是当前正在执行的脚本,并且“sys.path[0]”解决方案可以正常工作。但是,如果您的应用程序由脚本 A 组成,该脚本导入某个包“P”,然后调用脚本“B”,那么“PB”当前正在执行。如果您需要获取包含“PB”的目录,您需要“ os.path.realpath(__file__)
”解决方案。
“ __file__
”仅给出当前正在执行的(堆栈顶部)脚本的名称:“x.py”。它不提供任何路径信息。“os.path.realpath”调用才是真正的工作。
解决方案 5:
import os,sys
# Store current working directory
pwd = os.path.dirname(__file__)
# Append current directory to the python path
sys.path.append(pwd)
解决方案 6:
使用os.path.abspath('')
解决方案 7:
这对我有用(我是通过这个 stackoverflow 问题找到它的)
os.path.realpath(__file__)
解决方案 8:
import os
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep
解决方案 9:
这是我最终得到的结果。如果我将脚本导入解释器,或者将其作为脚本执行,那么这个方法对我有效:
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)
解决方案 10:
这是一个相当老的线程,但是当我尝试从 cron 作业运行 python 脚本时将文件保存到脚本所在的当前目录中时,我一直遇到这个问题。getcwd() 和许多其他路径都出现在您的主目录中。
获取我使用的脚本的绝对路径
directory = os.path.abspath(os.path.dirname(__file__))
解决方案 11:
import os
exec_filepath = os.path.realpath(__file__)
exec_dirpath = exec_filepath[0:len(exec_filepath)-len(os.path.basename(__file__))]
解决方案 12:
尝试一下:
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)