我一直在寻找解决方案,但没有找到我需要的。
脚本路径:/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__))
但是很丑。有更好的方法吗?
最佳答案
os.path.realpath 会给你结果:
os.path.dirname(os.path.realpath(__file__))
关于Python:脚本的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7293601/