Python获取脚本路径(三种方式)
2011-12-25 21:17
471 查看
|---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中获取路径的方式。
相关文章推荐
- Python输出内容的三种方式:print输出 python脚本执行 linux直接执行
- Python获取当前脚本绝对路径
- selenium java and python获取元素路径的几种方式和实例
- 命令行运行Python脚本时传入参数的三种方式
- python的subprocess:子程序调用(调用执行其他命令);获取子程序脚本当前路径问题
- 在python中,如何获取脚本文件所在路径
- Python 获取脚本路径以及脚本所在文件夹路径
- 命令行运行Python脚本时传入参数的三种方式
- shell,python获取当前路径(脚本的当前路径) (aso项目记录)
- python获取类名函数名、脚本路径
- Python 获取当前脚本文件路径目录
- python的subprocess:子程序调用(调用执行其他命令);获取子程序脚本当前路径问题
- Python语言获取脚本文件所在路径
- 【Python】获取windows桌面路径的5中方式
- shell,python获取当前路径(脚本的当前路径) (aso项目记录)
- python 获取脚本的绝对路径
- Python语言获取脚本文件所在路径
- Python获取脚本所在路径的方法
- python中获取执行脚本路径方法
- python 获取当前脚本所在路径