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

2012-06-28 Thread Alex chen
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 




--  --
??: "Dave Angel";
: 2012??6??28??(??) ????8:12
??: "Alex Chen"; 
: "python-list"; 
: Re: how can I implement "cd" like shell in Python?



On 06/28/2012 05:30 AM, ?? wrote:
> how can I implement "cd" like shell in Python?
>

import os
os.chdir("newdirectory")


But the more important question is why you want to.  Inside a Python
program, many people find that changing directory causes unexpected
difficulties, and they simply keep track of a full path instead, using
various os.path functions to manage it.

And once the python program ends, the shell should have no knowledge of
what you changed it to.

Now, a particular shell program might have some convention that allows a
program to inform it what directory to continue in.  But that's a
question about that shell, not about Python.  And you never said what
your environment is.


So give some more specifics to your needs, and somebody is likely to
know an approach.



-- 

DaveA-- 
http://mail.python.org/mailman/listinfo/python-list


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

2012-06-28 Thread Alex chen
OK,I see!

Thank you everyone.

 
 




-- Original --
From:  "Evan Driscoll";
Date:  Thu, Jun 28, 2012 10:27 PM
To:  "Alex chen"; 
Cc:  "d"; "python-list"; 
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-- 
http://mail.python.org/mailman/listinfo/python-list