Python 模块的搜索路径
设置PYTHONPATH环境变量
1
| $ export PYTHONPATH=$PYTHONPATH:/new/path/
|
通过sys.path来设置
1 2 3 4 5
| import sys
print (sys.path) print (sys.path.append('/new/path')) print (sys.path)
|
通过IDE来设置
根据不用的IDE,有不同的方法,一般在setting那里,
比如Pycharm或者VS code。
获取文件路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| print("获取当前文件路径——" + os.path.realpath(__file__))
parent = os.path.dirname(os.path.realpath(__file__)) print("获取其父目录——" + parent)
garder = os.path.dirname(parent) print("获取父目录的父目录——" + garder) print("获取文件名" + os.path.basename(os.path.realpath(__file__)))
pwd = os.getcwd() print("当前运行文件路径" + pwd)
father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".") print("运行文件父路径" + father_path)
grader_father = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..") print("运行文件父路径的父路径" + grader_father)
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| import os
curpath = os.path.realpath(__file__) print(curpath)
dirpath = os.path.dirname(curpath) print(dirpath)
casespath = os.path.join(dirpath, "cases") print(casespath)
report = os.path.join(dirpath, "report", "result.html") print(report)
|