Þ how can I implement "cd" like shell in Python?

Evan Driscoll driscoll at cs.wisc.edu
Thu Jun 28 10:27:05 EDT 2012


On 6/28/2012 7:28, Alex chen wrote:
> I just want to write a python program,it can be called in the linux
> terminal like the command "cd" to change the directory of the shell terminal

You "can't" do this; a program the shell runs cannot affect the shell's
execution.

What you have to do is have some help from the shell. Have your Python
program output the path to the directory you want to change to. Then you
can run it as follows
   cd $(new-directory.py)
or, if has arguments,
   cd $(new-directory.py foo blah)

(The $(...) is usually spelled as `...` around the internet. If you're
unfamiliar, what it does is run the command then substitute the *output*
of that command at the command line.)


Eventually you probably want to wrap this up so you don't have to do
that every time. You can use a shell function for this. Assuming you're
using an 'sh' derivative, it will look something like
   function my-cd() {
      cd $(new-directory.py "$@")
   }


I'm not a shell programmer and I always forget the names of the
variables holding the arguments, so check that at first and make sure
it's passing the right thing to the new-directory script, e.g. that it
works with whitespace in the arguments and that it isn't including the
equivalent to argv[0] in the script.

Evan



More information about the Python-list mailing list