kwsy
kwsy

Reputation: 39

Which one is more accurate, os.environ['PWD'] or os.getcwd()?

def getcwd():
    # get current path, try to use PWD env first
    try:
        a = os.stat(os.environ['PWD'])
        b = os.stat(os.getcwd())
        if a.st_ino == b.st_ino and a.st_dev == b.st_dev:
            cwd = os.environ['PWD']
        else:
            cwd = os.getcwd()
    except Exception:
        cwd = os.getcwd()
    return cwd

The code above is from gunicorn and is a function for getting the current working directory, with a preference for using the PWD environment variable. Notice the if condition in the code: it chooses to use PWD when the inodes and device numbers of the two directories match, and falls back to os.getcwd() when they don't. My confusion lies in the fact that os.getcwd() seems sufficiently accurate. Regardless of the if condition, simply using os.getcwd() should always provide the correct result, so why prioritize the PWD environment variable? In what situations would PWD be more accurate than os.getcwd()?

Upvotes: 0

Views: 57

Answers (2)

Amadan
Amadan

Reputation: 198456

os.environ['PWD'] is the value of the environment variable PWD, no more, no less. You can modify it by assigning to os.environ['PWD']; it does not affect the current working directory.

os.getcwd() is the current working directory, no more, no less. You can modify it with os.chdir; it does not affect the environment.

Demo:

import os

print("CWD:", os.getcwd())
print("PWD:", os.environ['PWD'])

print("os.chdir")
os.chdir('..')

print("CWD:", os.getcwd())
print("PWD:", os.environ['PWD'])

print("assignment to os.environ['PWD']")
os.environ['PWD'] = "whatever"

print("CWD:", os.getcwd())
print("PWD:", os.environ['PWD'])

Also try to run this program like this:

PWD=balderdash python3 demo.py

Unfortunately, I can't tell you which exact motivation led to the function in the OP. It is likely as user2357112 states: if PWD is not lying (like in my examples), based on whether they point to the same place as os.getcwd(), then it prefers PWD as it is more user-friendly - it is the path that the user would expect, as opposed to aaa that seems to return a canonical path.

Upvotes: 1

user2357112
user2357112

Reputation: 281758

It's not about accuracy. The function will only use the PWD value if that value is a path to the same directory os.getcwd() returns. However, PWD may be a different path to the same directory, particularly in the presence of symbolic links. In that case, the PWD value is preferred.

For example, if you do cd /foo and then run this program, and /foo is a symbolic link to /bar, PWD will be /foo, but os.getcwd() will report that the current directory is /bar.

Upvotes: 3

Related Questions