Tengis
Tengis

Reputation: 2809

change directory with python

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?

Upvotes: 5

Views: 3764

Answers (5)

MK.
MK.

Reputation: 34527

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")`

Upvotes: 2

Mel Nicholson
Mel Nicholson

Reputation: 3225

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()

Upvotes: 1

sampson-chen
sampson-chen

Reputation: 47267

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

^ this spawns 2 separate shells, try:

sh("cd /home; pwd")

Upvotes: 3

ThiefMaster
ThiefMaster

Reputation: 318508

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.

Upvotes: 6

cnicutar
cnicutar

Reputation: 182629

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.

Upvotes: 5

Related Questions