Find path to currently running file

How can I find the full path to the currently running Python script? That is to say, what do I have to put to achieve this:

Nirvana@bahamut:/tmp$ python baz.py
running from /tmp 
file is baz.py

__file__ is NOT what you are looking for. Don't use accidental side-effects

sys.argv[0] is always the path to the script (if in fact a script has been invoked) -- see http://docs.python.org/library/sys.html#sys.argv

__file__ is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0] .

Example:

C:junkso>type junksoscriptpathscript1.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:junkso>type python26libsite-packageswhereutils.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:junkso>python26python scriptpathscript1.py
script: sys.argv[0] is 'scriptpathscript1.py'
script: __file__ is 'scriptpathscript1.py'
script: cwd is 'C:junkso'
show_where: sys.argv[0] is 'scriptpathscript1.py'
show_where: __file__ is 'C:python26libsite-packageswhereutils.pyc'
show_where: cwd is 'C:junkso'

This will print the directory in which the script lives (as opposed to the working directory):

import os
dirname, filename = os.path.split(os.path.abspath(__file__))
print "running from", dirname
print "file is", filename

Here's how it behaves, when I put it in c:src :

> cd c:src
> python so-where.py
running from C:src
file is so-where.py

> cd c:
> python srcso-where.py
running from C:src
file is so-where.py

import sys, os

file = sys.argv[0]
pathname = os.path.dirname(file)
print 'running from %s' % os.path.abspath(pathname)
print 'file is %s' % file

检查os.getcwd()(docs)

链接地址: http://www.djcxy.com/p/54694.html

上一篇: 当前文件的路径取决于我如何执行程序

下一篇: 查找当前运行的文件的路径