@python __file__ and Argv[0]
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:
ImportMsnSysdirname, filename =Os.Path.Split(Os.path. ( [ ] "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__
- According to the relative path./test.py to execute, the print is the relative path,
- Absolute paths are obtained by absolute path execution.
- And according to 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.PyImportSysOsPrint"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.PyImportSysOsdef 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:CWDIsC\\junk\\so ' Show_where:Sys.Argv[0]Is' ScriptPath\\script1.py "Show_where: __file__ Span style= "color: #ff7700; Font-weight:bold; padding:0px; margin:0px; " >is C:\\python26\\lib\\site-packagesis ' C:
also OS.GETCWD (), get the absolute path to the folder
Choose different functions for different purposes
Python __file__ and Argv[0]