读书人

python _file_ 与argv[零]

发布时间: 2012-12-23 11:28:15 作者: rapoo

python __file__ 与argv[0]

python __file__ 与argv[0]

在python下,获取当前执行主脚本的方法有两个:sys.argv[0]和__file__。

sys.argv[0]

获取主执行文件路径的最佳方法是用sys.argv[0],它可能是一个相对路径,所以再取一下abspath是保险的做法,像这样:

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'

所以一般来说,argv[0]要更可靠些。

读书人网 >perl python

热点推荐