Changing a shell's current directory with python

A

Andy B.

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?

% pwd
/var/tmp
% myutil.py
# do some stuff and cd to '/var/log'
% pwd
/var/log

Many thanks,

-A
 
L

Lawrence Oluyede

irIl 2005-12-18 said:
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?

% pwd
/var/tmp
% myutil.py
# do some stuff and cd to '/var/log'
% pwd
/var/log

Just look in the library:

import os
os.chdir("path")
 
D

Dennis Lee Bieber

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?

That's about all you will be able to achieve... the inheritance goes
downwards: shell -> program(python, etc.) -> spawned processes
(os.system, etc.)... Changes at one level are only picked up by things
started after that change, and started from that level.
--
 
A

Andy B.

Many thanks for the sanity check. Just wanted to check with the gurus
before heading down another path.

-A
 
Joined
Jan 30, 2011
Messages
1
Reaction score
0
You can use alias to change your directory

I'm not sure whether this is helpful, but here's a common thing I do to change my directory using a python script:

1) Create a python script that does stuff and then prints a directory name.
2) Use an alias that calls that script and cd's to the output.

Here's an example that creates a directory in pwd from today's date and changes into it:

$ cd /tmp
$ cat > /tmp/test.py
#!/usr/bin/env python

import datetime
import os

today = datetime.date.today()
dir_string = today.strftime("%Y%m%d")
os.mkdir(dir_string)
print dir_string
$ chmod 755 /tmp/test.py
$ alias cdtoday='cd `/tmp/test.py`'
$ cdtoday
$ pwd
/tmp/20110129
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,187
Latest member
RosaDemko

Latest Threads

Top