5

I coincidentally found out that I cannot change the actual directory from within a python-code. My Test-Program is as follows:

from os import system

def sh(script):
    system("bash -c '%s'" % script)

sh("cd /home")
sh("pwd")

The output of pwd is not /home, but the directory where the code above lives.

Can someone explain why this happens?

1
  • You should use os.chdir() instead. Commented Dec 5, 2012 at 21:08

5 Answers 5

6

The problem is that you execute shell commands instead of actually changing the directory using os.chdir()

Each os.system() call executes the given command in a new shell - so the script's working directory is not affected at all.

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

Comments

5

The directory actually is changed, but in another process, the child of your script. There's one simple rule to remember: a child can never affect the environment (PATH, CWD etc) of its parent.

Comments

3
sh("cd /home")
sh("pwd")

^ this spawns 2 separate shells, try:

sh("cd /home; pwd")

Comments

2

When you run sh function you spawn a new bash process which then changes current directory and exits. Then you spawn a new process which knows nothing about what happened to the first bash process. Its current directory is, again, set to the home directory of the current user.
To change Python process' current working directory use

os.chdir("blah")`

Comments

1

Each sh( ) call is generating a different shell, so you are affecting the shell's working directory, not python's. To change pythons working directory, use chdir()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.