1

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!

1 Answers1

1

subprocess module creates new sub process and changes directory in for that process. it will not change directory of the parent process.

To change current process directory use os.chdir(target_dir)

More:

import os
os.chdir(<target_dir>) # to change directory
os.listdir('.') # to list current directory
os.listdir(<target_idr>) # to list target_dir
cedric
  • 331
  • 1
  • 6