-1

I ran into something interesting when bug testing some code, when i use os.chdir('/home') for example python will still show my cwd as whatever i started the interpreter from. Where it gets weird is the dir is actually being changed but the interpreter never shows this.

Is this some weird legacy of 2.7~ or is this something working as intended? I spent a while this morning trying to figure out why my directory was never changing inside the interpreter when it actually was.

Im using functions from import os, import sys and basic python commands.

Interpreter Setup: import os import sys

def findAHomeP(homeDir="randomDirName"):
    cwd = os.cwd()
    splitCwd = cwd.split('/')
    try:
        index = splitCwd.index(homeDir)
    except NameError as e:
        print "error stuff"
        return cwd

    newPath = '/'.join(splitCwd[0:index+1])+'/'

    return newPath

This code roughly returns a home dir for the desired location. Basically i was writing a test case to test this and make sure the results returned correctly. When i was going into the interpreter to test things before going to the next step i found that when you use the os.chdir(path) command it doesn't actually show the dir change in the python interpreter, it will still show whatever directory you started the interpreter from. E.g if i start the interpreter in /home/user/dir1/dir2/d5 it will always display that directory inside the interpreter if you use cwd. Even if you have changed it with os.chdir(newPath) which does work but the interpreter doesn't update the cwd for some reason.

1 Answers1

1

If you mean using the cwd variable, like print(cwd), then the issue is that you've set cwd to be the value returned by os.getcwd() at the start if your findAHomeP function, then later changed the current working directory with os.chdir(). If you want the new current working directory, you need to call os.getcwd() again, not use the (now stale) value stored in cwd.

mday
  • 78
  • 7
  • @mdayThis was all done through the interpreter on another stand alone system i have. The code was mostly just so people could get an idea of what i was doing with the interpreter. I believe the issue is that the interpreter uses a static value from where its running when using a basic cwd command vs the os.cwd() call which does an actual call to see what the cwd is vs just using cwd which returns a static value thats whatever directory you ran the interpreter from initially. – Richard Smith Aug 14 '18 at 11:34
  • @RichardSmith Neither the regular CPython interpreter, nor IPython, have a built-in `cwd` command. Without knowing more about the interpreter you're using, and how you're using it, I can't help more. – mday Aug 19 '18 at 22:21