平时写python经常会想获得脚本所在的目录,例如有个文件跟脚本文件放在一个相对的目录位置,那就可以通过脚本文件的目录找到对应的文件,即使以后脚本文件移到其他地方,脚本也基本不需要改动(相对于写死目录的好处)。下面通过一些代码进行一下对比。

这是我写的一段代码在:/root/printfabcd/py/filePath.py

  1. 20 logger.debug("sys.path:"+sys.path[0])
  2. 21 logger.debug("sys.argv:"+sys.argv[0])
  3. 22 logger.debug("__file__:"+__file__)
  4. 23 logger.debug("os.getcwd():"+os.getcwd())
  5. 24 logger.debug("os.path.realpath():"+os.path.realpath(__file__))
  6. 25 logger.debug("(os.path.abspath(__file__)):"+os.path.abspath(__file__))
  7. 26 logger.debug("os.path.dirname(os.path.realpath()):"+os.path.dirname(os.path.realpath(__file__)))
  8. 27 logger.debug("os.path.dirname(os.path.abspath(__file__)):"+os.path.dirname(os.path.abspath(__file__)))

在/root/printfabcd/py 目录下执行:python filePath.py

  1. 2011-11-27 13:20:20,090 DEBUG filePath 20 sys.path:/root/printfabcd/py
  2. 2011-11-27 13:20:20,090 DEBUG filePath 21 sys.argv:filePath.py
  3. 2011-11-27 13:20:20,090 DEBUG filePath 22 __file__:filePath.py
  4. 2011-11-27 13:20:20,090 DEBUG filePath 23 os.getcwd():/root/printfabcd/py
  5. 2011-11-27 13:20:20,091 DEBUG filePath 24 os.path.realpath():/root/printfabcd/py/filePath.py
  6. 2011-11-27 13:20:20,091 DEBUG filePath 25 (os.path.abspath(__file__)):/root/printfabcd/py/filePath.py
  7. 2011-11-27 13:20:20,091 DEBUG filePath 26 os.path.dirname(os.path.realpath()):/root/printfabcd/py
  8. 2011-11-27 13:20:20,091 DEBUG filePath 27 os.path.dirname(os.path.abspath(__file__)):/root/printfabcd/py

在/root 目录下执行:python printfabcd/py/filePath.py

2

  1. 2011-11-27 13:20:39,227 DEBUG filePath 20 sys.path:/root/printfabcd/py
  2. 2011-11-27 13:20:39,227 DEBUG filePath 21 sys.argv:printfabcd/py/filePath.py
  3. 2011-11-27 13:20:39,227 DEBUG filePath 22 __file__:printfabcd/py/filePath.py
  4. 2011-11-27 13:20:39,228 DEBUG filePath 23 os.getcwd():/root
  5. 2011-11-27 13:20:39,228 DEBUG filePath 24 os.path.realpath():/root/printfabcd/py/filePath.py
  6. 2011-11-27 13:20:39,228 DEBUG filePath 25 (os.path.abspath(__file__)):/root/printfabcd/py/filePath.py
  7. 2011-11-27 13:20:39,228 DEBUG filePath 26 os.path.dirname(os.path.realpath()):/root/printfabcd/py
  8. 2011-11-27 13:20:39,228 DEBUG filePath 27 os.path.dirname(os.path.abspath(__file__)):/root/printfabcd/py

从上面两个输出可以看出来,如果想获得脚本所在目录最简单就是通过sys.path[0],os.getcwd()获得的是执行脚本的目录。

下面在做一下测试 我在/root/printfabcd/py/下创建一个软连接tfilePath.py 指向filePath.py,执行tfilePath.py

  1. 2011-11-27 13:20:57,466 DEBUG tfilePath 20 sys.path:/root/printfabcd/py
  2. 2011-11-27 13:20:57,466 DEBUG tfilePath 21 sys.argv:printfabcd/py/tfilePath.py
  3. 2011-11-27 13:20:57,466 DEBUG tfilePath 22 __file__:printfabcd/py/tfilePath.py
  4. 2011-11-27 13:20:57,467 DEBUG tfilePath 23 os.getcwd():/root
  5. 2011-11-27 13:20:57,467 DEBUG tfilePath 24 os.path.realpath():/root/printfabcd/py/filePath.py
  6. 2011-11-27 13:20:57,467 DEBUG tfilePath 25 (os.path.abspath(__file__)):/root/printfabcd/py/tfilePath.py
  7. 2011-11-27 13:20:57,467 DEBUG tfilePath 26 os.path.dirname(os.path.realpath()):/root/printfabcd/py
  8. 2011-11-27 13:20:57,468 DEBUG tfilePath 27 os.path.dirname(os.path.abspath(__file__)):/root/printfabcd/py

仔细看os.path.realpath()和os.path.abspath()可以看出他们的区别,即使你创建了软连接,realpath还是可以拿到真正对应的文件。我是一个python的初学者懂得不多,如果发现什么问题,请多多指正。

下面是__file__与sys.argv[0]的一个对比

转载自:http://andylin02.iteye.com/blog/933237

python __file__ 与argv[0]

在python下,获取当前执行主脚本的方法有两个:sys.argv[0]和__file__。

sys.argv[0]

获取主执行文件路径的最佳方法是用sys.argv[0],它可能是一个相对路径,所以再取一下abspath是保险的做法,像这样:

import os,sys
dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
print "running from", dirname
print "file is", filename

__file__

__file__ 是用来获得模块所在的路径的,这可能得到的是一个相对路径,比如在脚本test.py中写入:

#!/usr/bin/env python
print __file__

  • 按相对路径./test.py来执行,则打印得到的是相对路径,
  • 按绝对路径执行则得到的是绝对路径。
  • 而按用户目录来执行(~/practice/test.py),则得到的也是绝对路径(~被展开)
  • 所以为了得到绝对路径,我们需要 os.path.realpath(__file__)。

而在Python控制台下,直接使用print __file__是会导致  name ‘__file__’ is not defined错误的,因为这时没有在任何一个脚本下执行,自然没有 __file__的定义了。

__file__和argv[0]差异

在主执行文件中时,两者没什么差异,不过要是在不同的文件下,就不同了,下面示例:

C:\junk\so>type \junk\so\scriptpath\script1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()
 
C:\junk\so>type \python26\lib\site-packages\whereutils.py
import sys, os
def show_where():
print "show_where: sys.argv[0] is", repr(sys.argv[0])
print "show_where: __file__ is", repr(__file__)
print "show_where: cwd is", repr(os.getcwd())
 
C:\junk\so>\python26\python scriptpath\script1.py
script: sys.argv[0] is 'scriptpath\\script1.py'
script: __file__ is 'scriptpath\\script1.py'
script: cwd is 'C:\\junk\\so'
show_where: sys.argv[0] is 'scriptpath\\script1.py'
show_where: __file__ is 'C:\\python26\\lib\\site-packages\\whereutils.pyc'
show_where: cwd is 'C:\\junk\\so'

所以一般来说,argv[0]要更可靠些。

python 获取脚本所在目录的更多相关文章

  1. Python获取脚本所在目录的正确方法(转)

    1.以前的方法如果是要获得程序运行的当前目录所在位置,那么可以使用os模块的os.getcwd()函数.如果是要获得当前执行的脚本的所在目录位置,那么需要使用sys模块的sys.path[0]变量或者 ...

  2. python获取文件所在目录

    1.执行的python程序获取自己文件所在目录 import os,sys os.chdir(sys.path[0]); dir_name = os.path.abspath(os.path.join ...

  3. Python入门之获取当前所在目录的方法详解

    #本文给大家讲解的是使用python获取当前所在目录的方法以及相关示例,非常的清晰简单,有需要的小伙伴可以参考下 sys.path 模块搜索路径的字符串列表.由环境变量PYTHONPATH初始化得到. ...

  4. Python获取程序运行目录和脚本目录

    Python获取程序运行目录和脚本目录 import os import sys #获取脚本所在目录 print os.path.split( os.path.realpath( sys.argv[0 ...

  5. shell脚本中获取当前所在目录地址

    shell脚本中获取当前所在目录如下 #!/bin/bash work_path=$() cd ${work_path} work_path=$(pwd) cd ${work_path}/src

  6. 获得Python脚本所在目录

    如何获得Python脚本所在目录的位置   On this page... (hide) 1.  以前的方法 2.  正确的方法 3.  实例说明   (Edit) 1.  以前的方法 如果是要获得程 ...

  7. [Python]切换工作目录|python将目录切换为脚本所在目录

    Python使用os.chdir命令切换python工作目录 代码示例: In []: import os In []: os.system("pwd") /home/wangju ...

  8. 【原创】ABAP根据文件路径获取文件所在目录(续)

    在上一篇文章<ABAP根据文件路径获取文件所在目录>中,我主要的思路是采用 “SPLIT dobj AT sep INTO TABLE result_tab” 句型将文件全路径按分隔符“\ ...

  9. 【原创】ABAP根据文件路径获取文件所在目录

    *&---------------------------------------------------------------------* *& Form frm_get_pat ...

随机推荐

  1. 使用Json出现java.lang.NoClassDefFoundError解决方法

    前几天在项目使用到Json格式数据,于是把使用Json需要用到的包都引到了工程里面,程序写好后运行时,发现后台报 java.lang.NoClassDefFoundError: net/sf/json ...

  2. iOS中事件传递过程

    iOS中,UIApplication管理着一个事件的队列,当系统获取用户的点击或滑动等事件后,就会将这些事件按顺序插入UIApplication管理的这个队里中,UIApplication再从这个队列 ...

  3. CentOS 7 Rescure

    之前从来没想过会在Linux系统中使用这个东西-- 今天系统无法启动了!!! 一.开机进度条卡住了.查看一下字符卡在哪里了? Starting MySQL Community Server... 就是 ...

  4. 如何让老Mac机支持USB安装Windows

    一些老Mac机的用户想装Windows,却发现自己的系统上的Boot Camp Assistant(以下简称BCA)没有USB安装Windows的选项. 下面以我的MacBook Pro (13-in ...

  5. python起的 simpleHTTPServer服务传输文件

    python起的 simpleHTTPServer服务传输文件 经同事的介绍,在Linux上传输文件的一种特别方便的方法: python -m SimpleHTTPServer [端口] 端口不填 默 ...

  6. android:layout_weight的真实含义(转)

    首先声明只有在Linearlayout中,该属性才有效.之所以Android:layout_weight会引起争议,是因为在设置该属性的同时,设置android:layout_width为wrap_c ...

  7. iOS自动化编译方案

    本文主要来源以下Bryce Zhang博主的文章,感谢博主的无私分享,转载请注明出处,尊重原创 然,根据Bryce Zhang文章进行实践过程中遇到一些问题,解决后在此做相应的总结.大神请绕道,觉得低 ...

  8. 高效的插入子节点DocumentFragment

    DocumentFragment 对象 DocumentFragment 接口表示文档的一部分(或一段).更确切地说,它表示一个或多个邻接的 Document 节点和它们的所有子孙节点. Docume ...

  9. windows php线程安全和不安全,两个版本我也看不懂,记下来再说。

    Windows下的PHP版本分两种:线程安全版本与非线程安全版本. 要论两者的区别,详细论说起来比较麻烦,从使用者的角度,记住什么时候用哪种版本的区别就可以了吧: 1.windows + IIS + ...

  10. 数据库DDL审计

    一.为什么需要数据库DDL审计? DDL在生产系统中扮演非常重要的作用. 1)首先从业务角度来说,DDL可能意味着表结构变更,意味着新的版本即将发布,是个重要的时刻. 2)其次从运维角度来说,DDL尤 ...