Python:脚本的目录

Mat*_*łło 7 python directory

我一直在寻找解决方案,但还没找到我需要的东西.

脚本路径:/dir/to/script/script.pyC:\ dir\script.py

例外结果:

$ ./script.py
output: /dir/to/script
$ cd .. && ./script/script.py
output: /dir/to/script
Run Code Online (Sandbox Code Playgroud)

os模块中有什么功能吗?


我混合解决方案写道:

print os.path.abspath(os.path.dirname(__file__))
Run Code Online (Sandbox Code Playgroud)

但它很难看.还有更好的方法吗?

Mu *_*iao 15

os.path.realpath会给你结果:

os.path.dirname(os.path.realpath(__file__))
Run Code Online (Sandbox Code Playgroud)

  • 它仍然是脆弱的,并假设有关cwd和脚本执行位置的某些事情.例如,将`os.chdir('/ tmp')`放在脚本中的上一行中,此解决方案可能会中断. (2认同)