faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 2 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

Finding directory of script

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 80, Fred L. Drake


"""
Packages: operating_systems.generic
"""
"""Support for 'logical' paths in Python.
This module replaces the functions os.chdir() and os.getcwd() when it's
possible to use logical path manipulations instead of physical path
manipulations.  Be aware that 'logical path' is a shell concept, and
doesn't normally affect applications.  But it should.  ;-)
To make this work, you may need to have 'export PWD' in your ~/.bashrc or
someplace equivalent.  If $PWD isn't defined in the environment, this module
is a no-op.
This module should be imported before either os.chdir() or os.getcwd() are
used to ensure everything is set up right.  Importing it after using
os.getcwd() is called may cause inconsistent results to be returned from
os.getcwd().
"""
__author__ = "Fred L. Drake, Jr. <fdrake@acm.org>"
__version__ = '$Revision$'
import os
if os.environ.get("PWD"):
    try:
        _os_getcwd
    except NameError:
        _os_getcwd = os.getcwd
        _os_chdir = os.chdir
    _cwd = os.environ["PWD"]
    def chdir(path):
        global _cwd
        p = os.path.normpath(os.path.join(_cwd, path))
        rc = _os_chdir(p)
        _cwd = p
        os.environ["PWD"] = p
        return rc
    def getcwd():
        return _cwd
    os.chdir = chdir
    os.getcwd = getcwd
else:
    chdir = os.chdir
    getcwd = os.getcwd