[py]python __file__ 与argv[0]

时间:2021-12-27 14:19:49

http://andylin02.iteye.com/blog/933237

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import os,sys
dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
print "running from", dirname
print "file is", filename
__file__ 是用来获得模块所在的路径的,这可能得到的是一个相对路径,比如在脚本test.py中写入:

#!/usr/bin/env python
print __file__

获取当前文件的全路径
获取全路径路径+文件名
···

!/usr/bin/env python

coding=utf-8

import os

print(file)

E:/learn/djangotest/mysite/demo/01.py

import sys

print(sys.argv[0])

E:/learn/djangotest/mysite/demo/01.py

print(os.path.abspath(sys.argv[0]))

E:\learn\djangotest\mysite\demo\01.py

dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
print(dirname)

E:\learn\djangotest\mysite\demo

···