Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #24616 > unrolled thread

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

Started byEvan Driscoll <driscoll@cs.wisc.edu>
First post2012-06-28 09:27 -0500
Last post2012-06-28 09:27 -0500
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Þ how can I implement "cd" like shell in Python? Evan Driscoll <driscoll@cs.wisc.edu> - 2012-06-28 09:27 -0500

#24616 — Re: Þ how can I implement "cd" like shell in Python?

FromEvan Driscoll <driscoll@cs.wisc.edu>
Date2012-06-28 09:27 -0500
SubjectRe: Þ how can I implement "cd" like shell in Python?
Message-ID<mailman.1608.1340894225.4697.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web