Why does not os.system("cd mydir") work and we have to use os.chdir("mydir") instead in python? [duplicate]
Asked Answered
P

3

7

I tried doing a "pwd" or cwd, after the cd, it does not seem to work when we use os.system("cd"). Is there something going on with the way the child processes are created. This is all under Linux.

Pralltriller answered 8/2, 2016 at 18:56 Comment(2)
@MalikBrahimi, huh? "System explorer"? I can't speak to Windows, but on POSIX systems, this is simply incorrect.Majesty
The accepted answer to python subprocess changing directory is fully applicable to this question as well.Majesty
T
9

The system call creates a new process. If you do system("cd .., you are creating a new process that then changes its own current working directory and terminates. It would be quite surprising if a child process changing its current working directory magically changed its parent's current working directory. A system where that happened would be very hard to use.

Turner answered 8/2, 2016 at 18:58 Comment(0)
M
16

os.system('cd foo') runs /bin/sh -c "cd foo"

This does work: It launches a new shell, changes that shell's current working directory into foo, and then allows that shell to exit when it reaches the end of the script it was called with.

However, if you want to change the directory of your current process, as opposed to the copy of /bin/sh that system() creates, you need that call to be run within that same process; hence, os.chdir().

Majesty answered 8/2, 2016 at 18:57 Comment(0)
T
9

The system call creates a new process. If you do system("cd .., you are creating a new process that then changes its own current working directory and terminates. It would be quite surprising if a child process changing its current working directory magically changed its parent's current working directory. A system where that happened would be very hard to use.

Turner answered 8/2, 2016 at 18:58 Comment(0)
C
6

os.system (which is just a thin wrapper around the POSIX system call) runs the command in a shell launched as a child of the current process. Running a cd in that shell only changes the current directory of that process, not the parent.

Cause answered 8/2, 2016 at 18:58 Comment(2)
Not strictly a subshell -- a subshell is a shell forked from a parent shell without an intervening exec*-family syscall. (I made this same mistake in the first revision of my own answer, but have since corrected it).Majesty
@CharlesDuffy: Will fix. Thanks Charles!Cause

© 2022 - 2024 — McMap. All rights reserved.