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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4934806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:13:32  来源:igfitidea点击:

How can I find script's directory with Python?

pythondirectorydjango-viewsgetcwd

提问by Jonathan

Consider the following Python code:

考虑以下 Python 代码:

import os
print os.getcwd()

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 /.

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

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

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

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.

更新:
总结的答案迄今-os.getcwd()os.path.abspath()两个给可能会或可能不会在脚本所在的目录当前工作目录。在我的网络主机设置中__file__,只提供没有路径的文件名。

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

Python 中没有任何方法可以(始终)接收脚本所在的路径吗?

采纳答案by Czarek Tomczak

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

你需要调用os.path.realpath__file__,这样,当__file__是不带路径的文件名,你仍然可以获得目录路径:

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

回答by Jonathan

Use os.path.abspath('')

os.path.abspath('')

回答by jbcurtin

import os,sys
# Store current working directory
pwd = os.path.dirname(__file__)
# Append current directory to the python path
sys.path.append(pwd)

回答by neuro

I use:

我用:

import os
import sys

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

As aiham points out in a comment, you can define this function in a module and use it in different scripts.

正如aiham 在评论中指出的那样,您可以在模块中定义此函数并在不同的脚本中使用它。

回答by RED MONKEY

Try sys.path[0].

试试sys.path[0]

To quote from the Python docs:

引用 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.

在程序启动时初始化,此列表的第一项path[0]是包含用于调用 Python 解释器的脚本的目录。如果脚本目录不可用(例如,如果以交互方式调用解释器或从标准输入读取脚本),path[0]则为空字符串,它指示 Python 首先搜索当前目录中的模块。请注意,脚本目录插入在作为PYTHONPATH.

Source: https://docs.python.org/library/sys.html#sys.path

来源:https: //docs.python.org/library/sys.html#sys.path

回答by Dan R

This worked for me (and I found it via the this stackoverflow question)

这对我有用(我通过this stackoverflow question找到了它)

os.path.realpath(__file__)

回答by Stan

import os
exec_filepath = os.path.realpath(__file__)
exec_dirpath = exec_filepath[0:len(exec_filepath)-len(os.path.basename(__file__))]

回答by beoliver

import os
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep

回答by Al Cramer

This code:

这段代码:

import os
dn = os.path.dirname(os.path.realpath(__file__))

sets "dn" to the name of the directory containing the currently executing script. This code:

将“dn”设置为包含当前正在执行的脚本的目录的名称。这段代码:

fn = os.path.join(dn,"vcb.init")
fp = open(fn,"r")

sets "fn" to "script_dir/vcb.init" (in a platform independent manner) and opens that file for reading by the currently executing script.

将“fn”设置为“script_dir/vcb.init”(以独立于平台的方式)并打开该文件以供当前正在执行的脚本读取。

Note that "the currently executing script" is somewhat ambiguous. If your whole program consists of 1 script, then that's the currently executing script and the "sys.path[0]" solution works fine. But if your app consists of script A, which imports some package "P" and then calls script "B", then "P.B" is currently executing. If you need to get the directory containing "P.B", you want the "os.path.realpath(__file__)" solution.

请注意,“当前正在执行的脚本”有些含糊不清。如果您的整个程序由 1 个脚本组成,那么这就是当前正在执行的脚本,并且“sys.path[0]”解决方案工作正常。但是,如果您的应用程序包含脚本 A,它导入一些包“P”然后调用脚本“B”,那么“PB”当前正在执行。如果您需要获取包含“PB”的目录,则需要“ os.path.realpath(__file__)”解决方案。

"__file__" just gives the name of the currently executing (top-of-stack) script: "x.py". It doesn't give any path info. It's the "os.path.realpath" call that does the real work.

" __file__" 只给出当前正在执行的(栈顶)脚本的名称:“x.py”。它不提供任何路径信息。真正起作用的是“os.path.realpath”调用。

回答by James

This is a pretty old thread but I've been having this problem when trying to save files into the current directory the script is in when running a python script from a cron job. getcwd() and a lot of the other path come up with your home directory.

这是一个很老的线程,但是当我从 cron 作业运行 python 脚本时,尝试将文件保存到脚本所在的当前目录时,我遇到了这个问题。getcwd() 和许多其他路径与您的主目录一起出现。

to get an absolute path to the script i used

获取我使用的脚本的绝对路径

directory = os.path.abspath(os.path.dirname(__file__))

directory = os.path.abspath(os.path.dirname(__file__))