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

Alex chen wustcsvstudio at
Thu Jun 28 16:33:34 CEST 2012

OK,I see!

Thank you everyone.


------------------ Original ------------------
From:  "Evan Driscoll"<driscoll at>;
Date:  Thu, Jun 28, 2012 10:27 PM
To:  "Alex chen"<wustcsvstudio at>; 
Cc:  "d"<d at>; "python-list"<python-list at>; 
Subject:  Re:   how can I implement "cd" like shell in Python?

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

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 $(
or, if has arguments,
   cd $( 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 $( "$@")

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.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list