本节列出常见的一些问题。
当前路径可以用'.'表示,再用os.path.abspath()将其转换为绝对路径:
- # -*- coding:utf-8 -*-
- # test.py
-
- import os
-
- print(os.path.abspath('.'))
-
运行结果:
- $ python3 test.py
- /Users/michael/workspace/testing
-
可以通过特殊变量__file__获取:
- # -*- coding:utf-8 -*-
- # test.py
-
- print(__file__)
-
输出:
- $ python3 test.py
- test.py
-
可以通过sys模块的argv获取:
- # -*- coding:utf-8 -*-
- # test.py
-
- import sys
-
- print(sys.argv)
-
输出:
- $ python3 test.py -a -s "Hello world"
- ['test.py', '-a', '-s', 'Hello world']
-
argv的第一个元素永远是命令行执行的.py文件名。
sys模块的executable变量就是Python命令可执行文件的路径:
- # -*- coding:utf-8 -*-
- # test.py
-
- import sys
-
- print(sys.executable)
-
在Mac下的结果:
- $ python3 test.py
- /usr/local/opt/python3/bin/python3.4
-