|---bin
|---test01.py
|---src
|---aaa.py
|---testcase
|---group01
|---pathtest.py
pathtest.py:
import os
import sys
import inspect
inspect.getfile(inspect.currentframe())和inspect.stack()[0][1]得到的是定义该函数的脚本文件的路径,包含脚本名称
inspect.stack()[1][1]得到的是调用该脚本的脚本文件的路径,包含脚本名称
#return the script path where the function is defined
def test():
this_file=inspect.getfile(inspect.currentframe())
path=os.path.abspath(os.path.dirname(this_file))
return path
#return the script path where the function is called
def script_path():
caller_file=inspect.stack()[1][1]
return os.path.abspath(os.path.dirname(caller_file))
#return the script path where the Python interpreter is started
def test02():
path=os.path.realpath(sys.argv[0])
if os.path.isfile(path):
path=os.path.dirname(path)
return os.path.abspath(path)
def current_path():
path=os.path.realpath(sys.path[0])
if os.path.isfile(path):
path=os.path.dirname(path)
return os.path.abspath(path)
else:
caller_file=inspect.stack()[1][1]
return os.path.abspath(os.path.dirname(caller_file))
aaa.py:
import sys
import os
import inspect
sys.path.append("..\\testcase\\group01")
import pathtest
#path="aaa"
#print pathtest.test()
def caller_func():
caller_path=pathtest.script_path()
return caller_path
def def_func():
def_path=pathtest.test()
return def_path
def real_func():
real_func=pathtest.test02()
return real_func
def curr_func():
cur_func=pathtest.current_path()
return cur_func
print caller_func()
print def_func()
print real_func()
print "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
test01.py:
import sys
import os
import inspect
sys.path.append("..\\src")
import aaa
def func_a():
return aaa.caller_func()
def func_b():
return aaa.def_func()
def func_c():
return aaa.real_func()
def func_d():
return aaa.curr_func()
print func_a()
print func_b()
print func_c()
print func_d()
参考:http://blog.csdn.net/bupteinstein/article/details/6534177
Python获取路径的三种情况:获取函数定义所在脚本路径,获取调用函数脚本所在路径,获取启动Python解释器脚本所在路径
最常用的方式就是pathtest.py中current_path中获取路径的方式。