如何正确确定当前脚本目录?我想看看在python中确定当前脚本目录的最佳方法是什么?我发现,由于调用python代码的方法很多,很难找到一个好的解决方案。以下是一些问题:__file__如果脚本是用exec, execfile__module__仅在模块中定义。用例:./myfile.pypython myfile.py./somedir/myfile.pypython somedir/myfile.pyexecfile('myfile.py')(来自另一个脚本,该脚本可以位于另一个目录中,并且可以具有另一个当前目录)。我知道没有完美的解决方案,但我正在寻找解决大多数情况的最佳方法。最常用的方法是os.path.dirname(os.path.abspath(__file__))但是,如果您从另一个exec().警告任何使用当前目录的解决方案都将失败,这可能根据脚本的调用方式而有所不同,或者在运行的脚本中进行更改。
3 回答

慕莱坞森
TA贡献1810条经验 获得超4个赞
os.path.dirname(os.path.abspath(__file__))
exec
/execfile
__file__
globals

翻阅古今
TA贡献1780条经验 获得超5个赞
execfile(...)
inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename))

慕沐林林
TA贡献2016条经验 获得超9个赞
#!/usr/bin/env pythonimport inspectimport osimport sysdef get_script_dir(follow_symlinks=True): if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze path = os.path.abspath(sys.executable) else: path = inspect.getabsfile(get_script_dir) if follow_symlinks: path = os.path.realpath(path) return os.path.dirname(path)print(get_script_dir())
execfile()
(sys.argv[0]
__file__
PYTHONPATH=/path/to/library.zip python -mscript_to_run
sys.frozen
realpath
添加回答
举报
0/150
提交
取消