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

Alex chen wustcsvstudio at vip.qq.com
Thu Jun 28 10:33:34 EDT 2012


OK,I see!

Thank you everyone.

 
 




------------------ Original ------------------
From:  "Evan Driscoll"<driscoll at cs.wisc.edu>;
Date:  Thu, Jun 28, 2012 10:27 PM
To:  "Alex chen"<wustcsvstudio at vip.qq.com>; 
Cc:  "d"<d at davea.name>; "python-list"<python-list at python.org>; 
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
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120628/7684be76/attachment.html>


More information about the Python-list mailing list