C:test [dir] getpath [file] path.py [dir] sub [file] sub_path.py
For example,
C: There is also a directory named sub in the test directory;
C: There is getpath.py in the test directory, sub_path.py in the sub directory, getpath.py calls sub_path.py;
We Execute getpath.py under C:test. if we were
If sys.path[0] is used in sub_path.py, what is actually obtained is the directory path "C:test" where getpath.py is located, because Python virtual
The machine starts execution from getpath.py. If you want to get the path of sub_path.py, then you have to do this:
os.path.split(os.path.realpath(__file__))[0]
Verification:
Then we execute python getpath/path under C:test. py, at this time, the values corresponding to various usages in sub_path.py are actually:
os.getcwd() "C:test", which takes the starting execution directory
sys.path[0] or sys.argv[0 ] "C:testgetpath", takes the directory where the initially executed script is located
os.path.split(os.path.realpath(__file__))[0] "C:testgetpathsub", takes the directory where __file__ is located The directory where the file sub_path.py is located