python中獲取執行腳本路徑方法


1、sys.path[0]:獲取執行腳本目錄絕對路徑

#每次執行腳本時,python會將執行腳本目錄加入PYTHONPATH環境變量中(sys.path獲取)
#!/usr/bin/python3

import os
import sys

print(sys.path)
print(sys.path[0])
執行結果:
[root@localhost tmp]# ./py_test1/pytest24.py 
['/tmp/py_test1', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/pip-9.0.1-py3.6.egg']
/tmp/py_test1

2、sys.argv[0]:獲取腳本執行本身路徑

#!/usr/bin/python3

import os
import sys

print(sys.argv[0])
執行1結果:
[root@localhost tmp]# ./py_test1/pytest24.py   #相對路徑執行腳本則會返回相對路徑
./py_test1/pytest24.py
執行2結果:
[root@localhost tmp]# /tmp/py_test1/pytest24.py  #絕對路徑執行腳本則返回絕對路徑
/tmp/py_test1/pytest24.py

  注:sys.argv[0]獲取得不是腳本目錄路徑,而是腳本本身執行時的路徑!

3、__file__:同sys.argv[0]相似,獲取腳本執行本身路徑:

#!/usr/bin/python3

import os
import sys

print("sys.argv[0] Output:",sys.argv[0])
print("__file Output:",__file__)
執行1結果:
[root@localhost tmp]# ./py_test1/pytest24.py   #相對路徑執行腳本則會返回相對路徑
sys.argv[0] Output: ./py_test1/pytest24.py
__file Output: ./py_test1/pytest24.p

執行2結果:
[root@localhost tmp]# /tmp/py_test1/pytest24.py  #絕對路徑執行腳本則會返回絕對路徑
sys.argv[0] Output: /tmp/py_test1/pytest24.py
__file Output: /tmp/py_test1/pytest24.py

  注:__file__獲取得不是腳本目錄路徑,而是腳本本身執行時的路徑!

4、os.path.abspath(__file__)和os.path.realpath(__file__):獲取腳本執行本身的絕對路徑

  通過獲取__file__路徑,然后轉換成絕對路徑

#!/usr/bin/python3

import os
import sys

print("__file Output:",__file__)
print(os.path.abspath(__file__))
print(os.path.realpath(__file__))
執行結果:
[root@localhost tmp]# ./py_test1/pytest24.py 
__file Output: ./py_test1/pytest24.py
/tmp/py_test1/pytest24.py
/tmp/py_test1/pytest24.py

注:os.path.abspath(__file__)和os.path.realpath(__file__)獲取得是腳本本身的絕對路徑!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM