I'm trying to implement my own version of the 'cd' command that presents the user with a list of hard-coded directories to choose from, and the user has to enter a number corresponding to an entry in the list. The program, named my_cd.py
for now, should then effectively 'cd' the user to the chosen directory. Example of how this should work:
/some/directory
$ my_cd.py
1) ~
2) /bin/
3) /usr
Enter menu selection, or q to quit: 2
/bin
$
Currently, I'm trying to 'cd' using os.chdir('dir')
. However, this doesn't work, probably because my_cd.py
is kicked off in its own child process. I tried wrapping the call to my_cd.py
in a sourced bash script named my_cd.sh
:
#! /bin/bash
function my_cd() {
/path/to/my_cd.py
}
/some/directory
$ . my_cd.sh
$ my_cd
... shows list of dirs, but doesn't 'cd' in the interactive shell
Any ideas on how I can get this to work? Is it possible to change my interactive shell's current directory from a python script?
Change your sourced
bash
code to:and your Python code to do all of its
cosmetic
output (messages to the users, menus, etc) onsys.stderr
, and, at the end, instead ofos.chdir
, justprint
(tosys.stdout
) the path to which the directory should be changed.Contrary to what was said, you can do this by replacing the process image, twice.
In bash, replace your my_cd function with:
Then your python script has to finish with:
Remember to
import os, sys
at the beginning of the script.But note that this is borderline hack. Your shell dies, replacing itself with the python script, running in the same process. The python script makes changes to the environment and replaces itself with the shell, back again, still in the same process. This means that if you have some other local unsaved and unexported data or environment in the previous shell session, it will not persist to the new one. It also means that rc and profile scripts will run again (not usually a problem).
This can't be done. Changes to the working directory are not visible to parent processes. At best you could have the Python script print the directory to change to, then have the sourced script actually change to that directory.
my_cd.py
:Usage:
For what its worth, since this question is also tagged "bash", here is a simple bash-only solution:
Now, this script must be source'd, not executed:
So,
To solve your case, you could have the command the user runs be an alias that sources a bash script, which does the dir selection first, then dives into a python program after the cd has been done.