1、源码
import os
import sys
CUR_DIR=sys.path[0]
PROGRAM_NAME=sys.argv[0]
SOURCE_FILE_ABS_PATH=os.path.join(CUR_DIR, PROGRAM_NAME)
if __name__ == "__main__":
print("Welcome Python test program...")
print("Directory is: ",CUR_DIR)
print("Program is :", PROGRAM_NAME)
print("Source code file absolute directory is: ", SOURCE_FILE_ABS_PATH)
运行结果:
D:\Python-test>python test.py
Welcome Python test program...
Directory is: D:\Python-test
Program is : test.py
Source code file absolute directory is: D:\Python-test\test.pyD:\Python-test>
2、分析
2.1、sys.path[0]
sys.path[0]:返回当前运行模块路径,且该路径为绝对路径。
2.2、sys.argv[0]
sys.argv[0]:返回当前运行模块名字。
2.3、os.path.join
os.path.join:合并路径,中间会增加一个字符'\'或者‘/’(视操作系统而定)