0%

Python脚本路径

怎样获取一个脚本的路径?

怎样获取执行脚本的绝对路径?怎样获取执行脚本的父绝对路径?怎样获取入口脚本的绝对路径?。。。
带着这些问题,我们进行一个简单的实验,获知这些问题的答案。

路径实验

路径设计

1
2
3
4
5
path
└── module_a
├── getpath.py
└── module_b
└── getpath.py

脚本内容

getpath.py脚本内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import os
import sys
from module_b import getpath

def print_path():
print(f'os.getcwd() is {os.getcwd()}')
print(f'sys.path[0] is {sys.path[0]}')
print(f'sys.argv[0] is {sys.argv[0]}')
print(f'__file__ is {__file__}')
print(f'os.path.dirname(__file__) is {os.path.dirname(__file__)}')
print(f'os.path.abspath(__file__) is {os.path.abspath(__file__)}')
print(f'os.path.realpath(__file__) is {os.path.realpath(__file__)}')
print(f'os.path.split(os.path.realpath(__file__))[0] is {os.path.split(os.path.realpath(__file__))[0]}')

print('------ module_a/getpath.py ------')
print_path()
print('---------------------------------')
print('------ module_a/module_b/getpath.py ------')
getpath.print_path()
print('------------------------------------------')

执行脚本

在path目录中执行脚本python module_a/getpath.py ,得到结果为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
------ module_a/getpath.py ------
os.getcwd() is /Users/vk/tmp/path
sys.path[0] is /Users/vk/tmp/path/module_a
sys.argv[0] is module_a/getpath.py
__file__ is module_a/getpath.py
os.path.dirname(__file__) is module_a
os.path.abspath(__file__) is /Users/vk/tmp/path/module_a/getpath.py
os.path.realpath(__file__) is /Users/vk/tmp/path/module_a/getpath.py
os.path.split(os.path.realpath(__file__))[0] is /Users/vk/tmp/path/module_a
---------------------------------
------ module_a/module_b/getpath.py ------
os.getcwd() is /Users/vk/tmp/path
sys.path[0] is /Users/vk/tmp/path/module_a
sys.argv[0] is module_a/getpath.py
__file__ is /Users/vk/tmp/path/module_a/module_b/getpath.py
os.path.dirname(__file__) is /Users/vk/tmp/path/module_a/module_b
os.path.abspath(__file__) is /Users/vk/tmp/path/module_a/module_b/getpath.py
os.path.realpath(__file__) is /Users/vk/tmp/path/module_a/module_b/getpath.py
os.path.split(os.path.realpath(__file__))[0] is /Users/vk/tmp/path/module_a/module_b
------------------------------------------

实验结论

由实验结果,可以得出如下结论。

获取执行命令的绝对路径

1
os.getcwd()

获取入口脚本的父绝对路径

1
sys.path[0]

获取执行脚本的绝对路劲

1
2
os.path.abspath(__file__)
os.path.realpath(__file__)

获取执行脚本的父绝对路径

1
os.path.split(os.path.realpath(__file__))[0]

获取文件/目录的父路径

1
os.path.dirname(__file__)
  • 本文作者: 好好学习的郝
  • 本文链接: https://www.voidking.com/dev-python-script-path/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!源站会及时更新知识点及修正错误,阅读体验也更好。欢迎分享,欢迎收藏~