在編程中經常需要用到當前腳本的工作目錄,以下是python腳本獲取當前工作目錄的語句。例test.py
- import inspect
- dir = inspect.getfile(inspect.currentframe())
- print dir
打印出的是當前語句所在的或者說是包含當前語句的函數所在的腳本的目錄。
放在/home/zhang/下執行:
./test.py 輸出./test.py
python test.py 輸出test.py
/home/zhang/test.py 輸出/home/zhang/test.py
我們要獲得的是路徑,下面的程序會實現:
- import os,inspect
- dir = inspect.getfile(inspect.currentframe())
- if os.path.isdir(dir):
- print dir
- elif os.path.isfile(dir):
- print os.path.dirname(dir)
執行/home/zhang/test.py 輸出/home/zhang
也可以用print __file__輸出效果是一樣的