How to run the cd command in the terminal through Python script?

I want to run cd command in the terminal through my Python script. I just discovered a module called subprocess, do you have any idea why the Popen() method doesn’t change the directory in the terminal, it seems like it changes the state only.

    if p:
	    return subprocess.Popen(['cd'], cwd = target_dir, shell = True)
    return 'directory does not exist'

Terminal:

<subprocess.Popen object at 0x7f805ef045e0>

When I changed the command, it seems working:

    if p:
	    return subprocess.Popen(['ls', '-a'], cwd = target_dir, shell = True)
    return 'directory does not exist'

Terminal:

<subprocess.Popen object at 0x7ff1ef1ec5e0>
.  ..  projects  books  resources  docs

Your help is much appreciated!

I’m afraid I’m not familiar with the subprocess module.

Whenever I’ve needed to change the working directory in Python, I’ve used the os module.
There’s a short tutorial here on using the os module to do that

1 Like

Thank you for your help, I will give it a try.

Because it is running that command in a new shell.