Python gets the current path implementation code
- 2020-06-01 10:10:57
- OfStack
Python gets the current path implementation code
import os,sys
Use sys.path [0], sys.argv [0], os.getcwd (), os.path.abspath (), os.path.realpath ()
sys.path is the list of search paths that Python will find for the module, sys.path [0] and sys.argv [0] are one thing because Python automatically adds sys.argv [0]
sys path.
If you execute python getpath\ getpath.py in the C:\test directory, os.getcwd () will print "C:\test", sys.path [0] will print "C:\test\getpath".
If you compile the Python script into an executable using the py2exe module, the output of sys.path [0] will also change:
If you package the dependent library as an zip file by default, sys.path [0] will output "C:\test\getpath\ libarary.zip";
If the zipfile=None parameter is specified in setup.py and the dependent library is packed into the exe file, sys.path [0] will output "C:\test\getpath\ getpath.exe".
#!/bin/env python
#-*- encoding=utf8 -*-
import os,sys
if __name__=="__main__":
print "__file__=%s" % __file__
print "os.path.realpath(__file__)=%s" % os.path.realpath(__file__)
print "os.path.dirname(os.path.realpath(__file__))=%s" % os.path.dirname(os.path.realpath(__file__))
print "os.path.split(os.path.realpath(__file__))=%s" % os.path.split(os.path.realpath(__file__))[0]
print "os.path.abspath(__file__)=%s" % os.path.abspath(__file__)
print "os.getcwd()=%s" % os.getcwd()
print "sys.path[0]=%s" % sys.path[0]
print "sys.argv[0]=%s" % sys.argv[0]
Output results:
D:\>python ./python_test/test_path.py
__file__=./python_test/test_path.py
os.path.realpath(__file__)=D:\python_test\test_path.py
os.path.dirname(os.path.realpath(__file__))=D:\python_test
os.path.split(os.path.realpath(__file__))=D:\python_test
os.path.abspath(__file__)=D:\python_test\test_path.py
os.getcwd()=D:\
sys.path[0]=D:\python_test
sys.argv[0]=./python_test/test_path.py
os.getcwd () "D:\" takes the initial execution directory
sys.path [0] or sys.argv [0] "D:\python_test" takes the directory where the script was initially executed
os.path.split (os.path.realpath :\python_test)[0] "D:\python_test", take the directory of the file test_path.py which is located with s 121en__
Get the current path correctly:
__file__ Is the currently executing file
# Get the current file __file__ The path of the
print "os.path.realpath(__file__)=%s" % os.path.realpath(__file__)
# Get the current file __file__ Where directory
print "os.path.dirname(os.path.realpath(__file__))=%s" % os.path.dirname(os.path.realpath(__file__))
# Get the current file __file__ Where directory
print "os.path.split(os.path.realpath(__file__))=%s" % os.path.split(os.path.realpath(__file__))[0]
Thank you for reading, I hope to help you, thank you for your support of this site!