che_kid
che_kid

Reputation: 203

How do I change directory in python so it remains after running the script?

I'm trying to change the terminal directory through a python script. I've seen this post and others like it so I know about os.chdir, but it's not working the way I'd like. os.chdir appears to change the directory, but only for the python script. For instance I have this code.

#! /usr/bin/env python
import os

os.chdir("/home/chekid/work2/")
print os.getcwd()

Unfortunately after running I'm still in the directory of the python script (e.g. /home/chekid) rather than the directory I want to be in. See below.

gandalf(pts/42):~> pwd
/home/chekid

gandalf(pts/42):~> ./changedirectory.py
/home/chekid/work2

gandalf(pts/42):~> pwd
/home/chekid

Any thoughts on what I should do?

Edit: Looks like what I'm trying to do doesn't exist in 'normal' python. I did find a work around, although it doesn't look so elegant to me.

 cd `./changedirectory.py`

Upvotes: 9

Views: 4569

Answers (4)

bjarmak
bjarmak

Reputation: 11

You can make your python print the directory you want to move to, and then call your script with cd "$(./python-script.py)". In condition your script actually does not print anything else.

Upvotes: 0

Peer Sommerlund
Peer Sommerlund

Reputation: 512

You can if you cheat: Make a bash script that calls your python script. The python script returns the path you want to change directory to. Then the bash script does the acctual chdir. Of course you would have to run the bash script in your bash shell using "source".

Upvotes: 5

Kevin
Kevin

Reputation: 30151

You can't. The shell's current directory belongs to the shell, not to you.

(OK, you could ptrace(2) the shell and make it call chdir(2), but that's probably not a great design, won't work on Windows, and I would not begin to know how to do it in pure Python except that you'd probably have to mess around with ctypes or something similar.)

You could launch a subshell with your current working directory. That might be close enough to what you need:

os.chdir('/path/to/somewhere')
shell = os.environ.get('SHELL', '/bin/sh')
os.execl(shell, shell)
# execl() does not return; it replaces the Python process with a new shell process

The original shell will still be there, so make sure you don't leave it hanging around. If you initially call Python with the exec builtin (e.g. exec python /path/to/script.py), then the original shell will be replaced with the Python process and you won't have to worry about this. But if Python exits without launching the shell, you'll be left with no shell open at all.

Upvotes: 6

chepner
chepner

Reputation: 531165

The current working directory is an attribute of a process. It cannot be changed by another program, such as changing the current working directory in your shell by running a separate Python program. This is why cd is always a shell built-in command.

Upvotes: 3

Related Questions