1、sys.argv
2、 _ _ file_ _
3、sys.path
4、os.getcwd()
5、参考资料
sys.argv保存的是脚本的指令参数列表,sys.argv[0]是“执行”脚本的名字。print(sys.argv[0])返回相对路径还是绝对路径,主要看你脚本的执行方式,如下:
#当前路径 (base) SchillerdeMacBook-Pro:numpy_test schillerxu$ pwd /Users/schillerxu/Documents/sourcecode/python/numpy_test #代码 (base) SchillerdeMacBook-Pro:numpy_test schillerxu$ cat 3.py import sys import os print(sys.argv) print(sys.argv[0]) #两种不同的执行方法对比 (base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py ['3.py'] 3.py (base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py ['/Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py'] /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py
如果获取的是相对路径,可以用os.path.abspath(sys.argv[0])得到绝对路径,用os.path.split()可以得到目录名和文件名,代码如下:
import sys import os path=sys.argv[0] abs_path=os.path.abspath(sys.argv[0]) dirname,filename=os.path.split(abs_path) print(path) print(abs_path) print(dirname,filename)
程序运行的结果如下:
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ pwd /Users/schillerxu/Documents/sourcecode/python/numpy_test (base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py 3.py /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py /Users/schillerxu/Documents/sourcecode/python/numpy_test 3.py
最后获得目录名和文件名。
__ file__是当前脚本的名字,如果在当前脚本使用, __ file__和sys.argv[0]效果是一样的,比如代码如下:
import sys import os print(__file__)
运行结果:
(base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python 3.py 3.py (base) SchillerdeMacBook-Pro:numpy_test schillerxu$ python /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py /Users/schillerxu/Documents/sourcecode/python/numpy_test/3.py
同样受到脚本执行参数的影响。
但是如果脚本互相引用,__ file__和sys.argv[0]结果略有不同,比如代码:
a.py
import sys def f(): print(sys.argv[0]) print(__file__)
3.py
import sys import os import a print(sys.argv[0]) print(__file__) a.f()
执行结果:
可以看到__file__返回的是被调用(当前)的文件,sys.argv[0]更多的是脚本执行的参数。
sys.path保存了python解释器的部分路径,可以自己试下,其中sys.path[0]是执行脚本所在的目录。
代码:
import sys import os print(sys.path[0])
结果:
$ python 3.py /Users/schillerxu/Documents/sourcecode/python/numpy_test
os.getcwd()返回的是工作目录,并不一定是脚本所在目录。
代码:
import sys import os print(os.getcwd())
运行结果:
联系客服