关于python获取当前脚本路径的方法很多,讨论也不少,例一, 例二, 例三等等,就不一一列举了。
多数给的结论都是: os.path.split(os.path.realpath(__file__))[0]
实验测试一下,额外加入了pyinstaller打包的exe程序测试:
import os, sys
print('os.getcwd():', os.getcwd())
print('dirname(sys.path[0]):',os.path.dirname(sys.path[0]))
print('dirname(abspath(sys.argv[0])):',os.path.dirname(os.path.abspath(sys.argv[0])))
print('dirname(realpath(__file__)):',os.path.dirname(os.path.realpath(__file__)))
实测结果:
C:\Users>python E:\WorkShop\Python\pathTest.py D:\tmp\test.txt
os.getcwd(): C:\Users
dirname(sys.path[0]): E:\WorkShop
dirname(abspath(sys.argv[0])): E:\WorkShop\Python
dirname(realpath(__file__)): E:\WorkShop\Python
C:\Users>E:\WorkShop\Python\pathTest.exe D:\tmp\test.txt
os.getcwd(): C:\Users
dirname(sys.path[0]): C:\Users\DIEGNI~1\AppData\Local\Temp\_MEI17442
dirname(abspath(sys.argv[0])): E:\WorkShop\Python
dirname(realpath(__file__)): C:\Users
C:\Users>E:
E:\>cd WorkShop\Python
E:\WorkShop\Python>pathTest.exe D:\tmp\test.txt
os.getcwd(): E:\WorkShop\Python
dirname(sys.path[0]): C:\Users\XIAONI~1\AppData\Local\Temp\_MEI12962
dirname(abspath(sys.argv[0])): E:\WorkShop\Python
dirname(realpath(__file__)): E:\WorkShop\Python
E:\WorkShop\Python>python pathTest.py D:\tmp\test.txt
os.getcwd(): E:\WorkShop\Python
dirname(sys.path[0]): E:\WorkShop
dirname(abspath(sys.argv[0])): E:\WorkShop\Python
dirname(realpath(__file__)): E:\WorkShop\Python
结论显而易见,用sys.argv[0]
是最靠谱的。
网友评论