Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change working directory in shell with a python script

I want to implement a userland command that will take one of its arguments (path) and change the directory to that dir. After the program completion I would like the shell to be in that directory. So I want to implement cd command, but with external program.

Can it be done in a python script or I have to write bash wrapper?

Example:

tdi@bayes:/home/$>python cd.py tdi
tdi@bayes:/home/tdi$>
like image 689
Darek Avatar asked Sep 24 '10 11:09

Darek


People also ask

How do you change the directory of a disc in Python?

You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to.

How do I change directory in Python shell?

Change the current working directory: os.chdir() Use the chdir() function in Python to change the current working directory. The path to the directory you wish to change to is the only parameter the method allows.

How do I change the working directory in shell?

Change Current Working Directory ( cd ) To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.

Which method is used to change the directory in Python?

chdir() method in Python used to change the current working directory to specified path.


2 Answers

Others have pointed out that you can't change the working directory of a parent from a child.

But there is a way you can achieve your goal -- if you cd from a shell function, it can change the working dir. Add this to your ~/.bashrc:

go() {
    cd "$(python /path/to/cd.py "$1")"
}

Your script should print the path to the directory that you want to change to. For example, this could be your cd.py:

#!/usr/bin/python
import sys, os.path
if sys.argv[1] == 'tdi': print(os.path.expanduser('~/long/tedious/path/to/tdi'))
elif sys.argv[1] == 'xyz':  print(os.path.expanduser('~/long/tedious/path/to/xyz'))

Then you can do:

tdi@bayes:/home/$> go tdi
tdi@bayes:/home/tdi$> go tdi
like image 162
bstpierre Avatar answered Sep 17 '22 21:09

bstpierre


That is not going to be possible.

Your script runs in a sub-shell spawned by the parent shell where the command was issued.

Any cding done in the sub-shell does not affect the parent shell.

like image 44
codaddict Avatar answered Sep 16 '22 21:09

codaddict