如何获取正在运行的Python脚本的路径?

2024-03-29 11:02:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何获取正在运行的Python脚本的路径?我在做dirname(sys.argv[0]),但是在Mac上我只得到文件名,而不是像在Windows上那样得到完整的路径。

无论应用程序从何处启动,我都希望打开与脚本文件相关的文件。


Tags: and文件ofthepathnamein路径
3条回答

os.path.realpath(__file__)将给出当前文件的路径,解析路径中的任何符号链接。这在我的mac上很管用。

import os
print os.path.abspath(__file__)

潜入Python的7.2:Finding the Path

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)) 

相关问题 更多 >