0

I'm writing a test script that is supposed to cd from the current directory into a new one if that path is confirmed to exist and be a directory

serial_number = input("Enter serial number: ")
directory = "/etc/bin/foo"
if os.path.exists(directory) and os.path.isdir(directory):
   #cd into directory?
   subprocess.call(['cd ..' + directory])

My dilemma is that I don't know how to properly pass a variable into a subprocess command, or whether or not I should use call or Popen. When I try the above code, it comes back with an error saying that No such file or directory "cd ../etc/bin/". I need is to travel back one directory from the current directory so then I can enter /etc and read some files in there. Any advice?

pjano1
  • 143
  • 1
  • 3
  • 10
  • 2
    Using `subprocess` to run `cd` is almost always going to be useless; it only changes the working directory for the forked subprocess, leaving the current working directly unchanged once `subprocess.call` returns. This is also true if you are expecting the working directory to have changed after your Python process exits. – chepner Jan 24 '19 at 18:30

4 Answers4

6

To change working directory of use

os.chdir("/your/path/here")

subprocess will spawn new process and this doesn't affect your parent.

Alex Maystrenko
  • 1,091
  • 10
  • 11
2

you should use os.chdir(directory) and then call to open your process. I imagine this would be more straightforward and readable

Reedinationer
  • 5,661
  • 1
  • 12
  • 33
  • 1
    It's more than just "straightforward" and "readable": it's the only possible way that *actually works*. Doing a `cd` in a subprocess has absolutely no effect on the parent process. – jasonharper Jan 24 '19 at 18:30
2

If you want to get one folder back, Just do it as you do in the shell.

os.chdir('..')

or in your case, you can,

directory = "/etc/bin/foo"
if os.path.exists(directory) and os.path.isdir(directory):
    os.path.normpath(os.getcwd() + os.sep + os.pardir)

Output will be: "/etc/bin"

byal
  • 167
  • 1
  • 12
1

It is not possible to change current directory using a subprocess, because that would change the current directory only withing the context of that subprocess and would not affect the current process.

Instead, to change the current directory within the Python process, use Python's function which does that: os.chdir, e.g.:

os.chdir('../etc/bin/')

On the other hand, if your idea is that the Python script does nothing else, but just change directory and than exit (this is how I understood the question), that won't work either, because when you exit the Python process, current working directory of the parent process will again not be affected.

zvone
  • 18,045
  • 3
  • 49
  • 77