Change caller's current working directory in Python
Question: I'm writing a simple script which ideally will help me conveniently change
directories around my system.

The details of the implementation don't matter, but let's say ideally I will
place this script in `/usr/bin` and call it with an argument denoting where I
want to go to on the system: `goto project1`

I would expect that when the script exits, my terminal's current working would
have changed to that of Project 1.

In order to accomplish this, I tried:

    
    
    os.chdir('/')
    
    subprocess.call('cd /', shell=True)
    

Neither of which work. The first changes the working directory in Python and
the second spawns a shell at `/`.

Then I realized how naive I was being. When a program is run, the terminal is
just forking a process, while reading from stdout, which my program is writing
to. Whatever it does, it wouldn't affect the state of terminal.

But then I thought "I've been using `cd` for years, surely someone wrote code
for that", thinking there might be something to go off of (system call or
something?).

But `cd` is not even
[coreutils](http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=tree;f=src;h=7c41b3fb7c90ccb1f66a7fb4bcdae16fcbd8fae5;hb=HEAD).
Instead, the source of `cd` is this:

    
    
    builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"}
    

So, a couple of questions come to mind:

  * What's actually going on behind the scenes when a user calls `cd`? (Meaning, how is the terminal and the system actually interacting?)
  * Is it possible to have something like a Python script alter the terminal location?

Thanks so much for your help!


Answer: You could do it as a pair of scripts:

**directory.py**

    
    
    #!/usr/bin/python
    
    import sys
    
    directory =  sys.argv[1]
    
    # do something interesting to manipulate directory...
    
    print directory + "tmp"
    

**directory.csh**

    
    
    #!/bin/csh -f
    
    cd `python directory.py $1`
    

**Result:**

    
    
    > pwd
    /Users/cdl
    > source directory.csh "/"
    > pwd
    /tmp
    > 
    

Substitute your favorite shell and variant of Python as desired. Turn on
execute for the Python script to simplify further.

Clearly the shell is changing the directory but Python can do all the clever
logic you want to figure out where to send the shell.

