🦍 maniedzi's blog

TIL: python and CWD

Today I learned that executing the "cd" command using "subprocess.run" does not change the current working directory. Obviously it does not, but I learned this the hard way.

Consider the following commands in REPL:

>>> import subprocess
>>>
>>> subprocess.run("ls", shell=True, stderr=subprocess.STDOUT)
Desktop  Documents  Downloads  Screenshots  snap  work
CompletedProcess(args='ls', returncode=0)
>>>
>>> subprocess.run("cd Documents", shell=True, stderr=subprocess.STDOUT)
CompletedProcess(args='cd Documents', returncode=0)
>>>
>>> subprocess.run("ls", shell=True, stderr=subprocess.STDOUT)
Desktop  Documents  Downloads  Screenshots  snap  work
CompletedProcess(args='ls', returncode=0)

It shows clearly that cd Documents is not changing the current working directory to "Documents"; it just executes the command, and that's it.

We can additionally check it by calling os.getcwd():

>>> import os
>>> import subprocess
>>>
>>> os.getcwd()
'/home/maniedzi'
>>>
>>> subprocess.run("cd Documents", shell=True, stderr=subprocess.STDOUT)
CompletedProcess(args='cd Documents', returncode=0)
>>>
>>> os.getcwd()
'/home/maniedzi'

So, in the example above, to change the current working directory, it is needed to call os.chdir("Documents").

#work