在python下,獲取當(dāng)前執(zhí)行主腳本的方法有兩個(gè):sys.argv[0]和__file__。
獲取主執(zhí)行文件路徑的最佳方法是用sys.argv[0],它可能是一個(gè)相對(duì)路徑,所以再取一下abspath是保險(xiǎn)的做法,像這樣:
__file__ 是用來(lái)獲得模塊所在的路徑的,這可能得到的是一個(gè)相對(duì)路徑,比如在腳本test.py中寫入:
#!/usr/bin/env python
print __file__
而在Python控制臺(tái)下,直接使用print __file__是會(huì)導(dǎo)致 name ‘__file__’ is not defined錯(cuò)誤的,因?yàn)檫@時(shí)沒(méi)有在任何一個(gè)腳本下執(zhí)行,自然沒(méi)有 __file__的定義了。
在主執(zhí)行文件中時(shí),兩者沒(méi)什么差異,不過(guò)要是在不同的文件下,就不同了,下面示例:
C:/junk/so>type /junk/so/scriptpath/script1.pyimport sys, osprint "script: sys.argv[0] is", repr(sys.argv[0])print "script: __file__ is", repr(__file__)print "script: cwd is", repr(os.getcwd())import whereutilswhereutils.show_where() C:/junk/so>type /python26/lib/site-packages/whereutils.pyimport sys, osdef show_where(): print "show_where: sys.argv[0] is", repr(sys.argv[0]) print "show_where: __file__ is", repr(__file__) print "show_where: cwd is", repr(os.getcwd()) C:/junk/so>/python26/python scriptpath/script1.pyscript: sys.argv[0] is 'scriptpath//script1.py'script: __file__ is 'scriptpath//script1.py'script: cwd is 'C://junk//so'show_where: sys.argv[0] is 'scriptpath//script1.py'show_where: __file__ is 'C://python26//lib//site-packages//whereutils.pyc'show_where: cwd is 'C://junk//so'
所以一般來(lái)說(shuō),argv[0]要更可靠些。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注