Under Python, there are two ways to get the current execution of the main script: Sys.argv[0] and __file__.
SYS.ARGV[0]
The best way to get the main execution file path is to use sys.argv[0], which may be a relative path, so it's safe to take a second abspath, like this:
Import os,sysdirname, filename = Os.path.split (Os.path.abspath (sys.argv[0])) print "Running from", Dirnameprint "file is ", filename
__file__
__FILE__ is used to get the path of the module, which may be a relative path, such as writing in script test.py:
#!/usr/bin/env python
Print __file__
- by relative path./test.py to execute, the print gets a relative path,
- An absolute path is obtained by performing the absolute path.
- And by the user directory to execute (~/practice/test.py), the resulting is also the absolute path (~ is expanded)
- So in order to get the absolute path, we need Os.path.realpath (__file__).
In the Python console, the direct use of print __file__ causes the name ' __file__ ' is not defined error, because there is no script executed at this time, naturally there is no __file__ definition.
__file__ and Argv[0] Differences
In the main execution file, there is no difference between the two, but if it is different under different files, the following example:
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 ' 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] should be more reliable.
Python's __file__ and Argv[0]