Python:脚本所在目录
我在寻找解决方案,但还没有找到我需要的。
脚本路径:/dir/to/script/script.py 或者 C:\dir\script.py
期望的结果:
$ ./script.py
output: /dir/to/script
$ cd .. && ./script/script.py
output: /dir/to/script
在os模块里有没有什么函数可以用呢?
我把几种解决方案混合在一起写了:
print os.path.abspath(os.path.dirname(__file__))
但是这样看起来不太好,有没有更好的方法呢?
1 个回答
15
os.path.realpath 会给你返回这样的结果:
os.path.dirname(os.path.realpath(__file__))