Changing a shell's current directory with python
Trent Mick
trentm at ActiveState.com
Tue Dec 20 22:01:19 EST 2005
[Peter Hansen wrote]
> Andy B. wrote:
> > I've got a python utility that I want to change my shell's current
> > directory based on criteria it finds. I've scoured google and the
> > python cookbook and can't seem to figure out if this is even possible.
> > So far, all my attempts have changed the current python session only.
> > Am I going to have to wrap this in a shell script?
>
> As you've heard, you can't get there from here. In fact, even just
> wrapping with a shell script likely won't be enough, unless you are
> willing to "source" the script every time you run it. The only way I
> know of (and I'd be happy to hear alternatives) to do this in a
> _transparent_ manner is to combine an alias (which uses "source" for
> you) with a wrapper script _and_ to have that wrapper script read from
> some place (stdout or a temporary file or ?) to which the Python script
> can communicate the desired new environment variables and/or current
> directory.
I do basically this with a script I have (http://trentm.com/projects/go)
for doing exactly what Andy requested: changing directories.
On Un*x you setup a shell function (like an alias),
which calls the Python script go.py,
which writes a shell script that changes the directory,
which gets 'source'd by the shell function.
function go ()
{
go_is_on_path="`\which go`";
if test -e "$go_is_on_path"; then
export GO_SHELL_SCRIPT=$HOME/.__tmp_go.sh;
python `\which go` $*;
if [ -f $GO_SHELL_SCRIPT ]; then
source $GO_SHELL_SCRIPT;
fi;
else
echo "ERROR: could not find 'go' on your PATH";
fi
}
On Windows 'go' does the same thing with a batch file.
Trent
--
Trent Mick
TrentM at ActiveState.com
More information about the Python-list
mailing list