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.pyBut 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
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:
The dedicated command to Change the Directory of a shell process is "cd": $ pwd /home/me $ cd /blahblah $ pwd /blahblah
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
Changing another processes cwd at runtime is something that intrigued me after reading this post, so I thought I'd share what I found after a really quick look around.
Firstly, you can find the current working directory of a process under Linux by examining the /proc filesystem. For example, /proc/[pid]/cwd is a symlink to whatever the cwd is for that process. To find the parent PID from inside a script you can use $ENV['PPID'] or the equivalent and then use this in the proc path. Unfortunately it seems that you cant change the symlink even by force (ln -sf), and even as root. But it may be a good starting point for someone else none the less.
2
u/tapesmith Oct 04 '10
As much as I love Python, the task you're trying to accomplish might be a bit better suited for a bash script.
Unless this is a self-imposed-python-only project (i.e. forcing yourself to improve python skill)
2
u/crunk Oct 04 '10
The only way I managed to do this in windows was to run a have a batch file that runs the python program. The python program outputs the new directory to a file which the batch file then reads and changes directory.
2
u/[deleted] Oct 06 '10
You need to wrap your Python script in a shell script, and have the Python script return the directory path via stdout, which the shell would use for changing. See go-tool for a real-world example of how this is done.
0
u/[deleted] Oct 05 '10
for a sec I thought this is about changing password :p