python __file__ and argv [0]

Source: http: //andylin02.iteye.com/blog/933237

python __file__ and argv [0]

In python, the current execution of the main script acquiring method There are two: sys.argv [0] and __file__.

sys.argv[0]

The best way to get the main executable file path is sys.argv [0], it could be a relative path, then take it abspath insurance practices, like this:

import os,sys
dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
print "running from", dirname
print "file is", filename

__file__

__file__ path is used to obtain the module resides, it is possible to obtain a relative path, such as a script written in test.py:

#!/usr/bin/env python
print __file__

  • ./test.py be performed in the relative path, the print is obtained relative path,
  • In absolute path to execute the resulting absolute path.
  • And by the user to perform directory (~ / practice / test.py), the absolute path is obtained (~ is expanded)
  • So in order to get the absolute path, we need os.path.realpath (__ file__).

While in the Python console directly print __file__ will lead name '__file__' is not defined wrong, because then not implemented in any script, there will be no definitions of the __file__.

__file__ and argv [0] Difference

When the main executable file, no difference between the two, but if in a different file, is different, the following examples:

C:\junk\so>type \junk\so\scriptpath\script1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()
 
C:\junk\so>type \python26\lib\site-packages\whereutils.py
import sys, os
def 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.py
script: 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'

So, in general, argv [0] to be more reliable.

Reproduced in: https: //www.cnblogs.com/stevenzeng/p/5234607.html

Guess you like

Origin blog.csdn.net/weixin_33887443/article/details/93881080