如何找到脚本的目录? [英] How can I find script's directory?

查看:73
本文介绍了如何找到脚本的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Python代码:

Consider the following Python code:

import os
print os.getcwd()

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

I use os.getcwd() to get the script file's directory location. When I run the script from the command line it gives me the correct path whereas when I run it from a script run by code in a Django view it prints /.

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

How can I get the path to the script from within a script run by a Django view?

更新:
总结到目前为止的答案- os.getcwd() os.path.abspath()都给出当前的工作目录,该目录可能是也可能不是脚本驻留.在我的Web主机设置中, __ file __ 仅提供文件名,而不提供路径.

UPDATE:
Summing up the answers thus far - os.getcwd() and os.path.abspath() both give the current working directory which may or may not be the directory where the script resides. In my web host setup __file__ gives only the filename without the path.

Python中是否没有办法(总是)能够接收脚本所在的路径?

Isn't there any way in Python to (always) be able to receive the path in which the script resides?

推荐答案

您需要在 __ file __ 上调用 os.path.realpath ,以便在 __ file__时是没有路径的文件名,您仍然会得到dir路径:

You need to call os.path.realpath on __file__, so that when __file__ is a filename without the path you still get the dir path:

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

这篇关于如何找到脚本的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆