问题描述
我想看看在 Python 中确定当前脚本目录的最佳方法是什么.
I would like to see what is the best way to determine the current script directory in Python.
我发现,由于调用 Python 代码的方式很多,很难找到一个好的解决方案.
I discovered that, due to the many ways of calling Python code, it is hard to find a good solution.
这里有一些问题:
- 如果使用
__file__
未定义__module__
仅在模块中定义
exec
、execfile
执行脚本,则 __file__
is not defined if the script is executed withexec
,execfile
__module__
is defined only in modules
用例:
./myfile.py
python myfile.py
./somedir/myfile.py
python somedir/myfile.py
execfile('myfile.py')
(来自另一个脚本,可以位于另一个目录中,并且可以有另一个当前目录.
./myfile.py
python myfile.py
./somedir/myfile.py
python somedir/myfile.py
execfile('myfile.py')
(from another script, that can be located in another directory and that can have another current directory.
我知道没有完美的解决方案,但我正在寻找解决大多数情况的最佳方法.
I know that there is no perfect solution, but I'm looking for the best approach that solves most of the cases.
最常用的方法是 os.path.dirname(os.path.abspath(__file__))
但是如果您使用 exec 从另一个脚本执行脚本,这确实不起作用()
.
The most used approach is os.path.dirname(os.path.abspath(__file__))
but this really doesn't work if you execute the script from another one with exec()
.
任何使用当前目录的解决方案都会失败,这可能会因调用脚本的方式不同而有所不同,也可以在正在运行的脚本中进行更改.
Any solution that uses current directory will fail, this can be different based on the way the script is called or it can be changed inside the running script.
推荐答案
os.path.dirname(os.path.abspath(__file__))
确实是您将要得到的最好的.
is indeed the best you're going to get.
使用 exec
/execfile
执行脚本是不寻常的;通常您应该使用模块基础结构来加载脚本.如果您必须使用这些方法,我建议您在传递给脚本的 globals
中设置 __file__
以便它可以读取该文件名.
It's unusual to be executing a script with exec
/execfile
; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting __file__
in the globals
you pass to the script so it can read that filename.
没有其他方法可以在执行代码中获取文件名:正如您所注意到的,CWD 可能位于完全不同的位置.
There's no other way to get the filename in execed code: as you note, the CWD may be in a completely different place.
这篇关于如何正确确定当前脚本目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!