python获取程序执行文件路径方法

python脚本打包成exe文件获取当前路径

import os
import sys
# 确定应用程序是脚本文件还是被冻结的exe
if getattr(sys, 'frozen', False):
    # 获取应用程序exe的路径
    path = os.path.dirname(sys.executable)
elif __file__:
    # 获取脚本程序的路径
    path = os.path.dirname(__file__) 
print(path)

python脚本获取当前文件的路径

import sys
import os
 
print(os.path.dirname(os.path.realpath(sys.executable)))
print(os.path.dirname(os.path.realpath(sys.argv[0])))

输出

D:\Users\MrFlySand\AppData\Local\Programs\Python\Python310
D:\Users\MrFlySand\Desktop\testPy\路径问题

获取py保存位置的目录

import sys
import os
print(sys.executable)
print(sys.prefix)

输出

D:\Users\MrFlySand\AppData\Local\Programs\Python\Python310\python.exe
D:\Users\MrFlySand\AppData\Local\Programs\Python\Python310
posted @ 2022-11-08 16:08  MrFlySand-飞沙  阅读(592)  评论(0编辑  收藏  举报