How do I get the path of a the Python script I am running in?

Duplicate:
In Python, how do I get the path and name of the file that is currently executing?

How do I get the path of a the Python script I am running in? I was doing dirname(sys.argv[0]) , however on Mac I only get the filename - not the full path as I do on Windows.

No matter where my application is launched from, I want to open files that are relative to my script file(s).


os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.


深入Python入门:寻找路径。

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

import os
print os.path.abspath(__file__)
链接地址: http://www.djcxy.com/p/42310.html

上一篇: 原子写入Python文件

下一篇: 我如何获得我正在运行的Python脚本的路径?