如何使用Python查找脚本的目录? [英] How can I find script's directory with Python?

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

问题描述

考虑以下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 )都给出当前工作目录,该目录可能是也可能不是脚本所在的目录。在我的网络主机设置中 __ 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__)))

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

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