1

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?

1
  • 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. Commented Jan 24, 2019 at 18:30

4 Answers 4

7

To change working directory of use

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

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.
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"

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.