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

1

u/samfoo Oct 04 '10

You're changing the current working directory (cwd; pwd means 'print working directory') of your python script, not of your shell process. You can see what your current working directory is for your script by calling os.getcwd().

1

u/[deleted] Oct 04 '10

How can I change cwd of shell process then? Is there an any dedicated command to do so or do I have to go through system call. Thanks.

3

u/samfoo Oct 04 '10

There's probably something very tricky that I don't know about, but in general: no, and you shouldn't want to.

What's the larger problem that you're trying to solve? There's nothing you shouldn't be able to do by changing the working directory of your python script and executing something and this way you maintain portability too.

1

u/[deleted] Oct 04 '10 edited Oct 04 '10

My main goal was to create simple python script to move my cwd up by using the given argument as a filter, and I was thinking to assign that to alias. So it would work something like this.

$ pwd
/home/aaa/bbb/ccc
$ python up.py aaa
$ pwd
/home/aaa

I never thought this simple task can be this complex.

btw, os.system('cd /blahblah') also didn't work for some reason. So I'll just give up. Thanks for your help though!

1

u/chadmill3r Py3, pro, Ubuntu, django Oct 04 '10 edited Oct 04 '10

The current working directory is just a local setting in the program. It's a variable. Outside your program, the variable means nothing because it went away when the program exited. If in one program, like your shell, you want to change something then you have to change the variable in that program. Use the shell command "cd" to do that. Note, "cd" is not a program. It's not in your path. It's not on the filesystem. It's a special string inside the shell only that changes the pwd variable.

And be careful with the words "system call". That means executing a function that the kernel implements, like "open()" or "write()"

You're mixing up shell functions, userspace/library functions, and system calls. Once you understand the differences and what is which, you'll be much more successful.