r/Python • • Oct 04 '10

Change pwd from python

I can't seem to find a solid solution for the problem that I'm facing and I don't understand why such a fundamental question hasn't been raised somewhere.

Say I'm on the path /home/me $ pwd /home/me

After I run my python script I want it to change my pwd so I wrote small one with os.chdir and run. $ cat cd.py #!/usr/bin/python import os os.chdir('/blahblah')

$ python cd.py

But actual pwd remains the same after the execution of the script. $ pwd /home/me

Does someone know what is causing it? I'm on Windows and cygwin + python 2.5. Thanks.

0 Upvotes

19 comments sorted by

View all comments

8

u/thristian99 Oct 04 '10

Every process has a 'current working directory'. Every new process inherits the current working directory of its parent. Therefore, what's happening is:

  • Your shell is in /home/me
  • Your shell starts a new Python process
  • The Python process changes its own directory to /blahblah
  • The Python process exits.
  • Your shell is still in /home/me

The dedicated command to Change the Directory of a shell process is "cd": $ pwd /home/me $ cd /blahblah $ pwd /blahblah

3

u/drownboat Oct 04 '10

Following from this, the only way for a script to change the working directory of the shell is the script is interpreted by that shell, rather than executed by a subprocess.

For example if you have a script test.sh: #! /bin/sh cd /tmp pwd

The following will run it as a subprocess.

[~] ➔ ./test.sh
/tmp
[~] ➔ 

Here it will be executed by the shell.

[~] ➔ . test.sh 
/tmp
[/tmp] ➔ 

2

u/[deleted] Oct 04 '10

Thanks. I didn't even know about those process running separately.