Krishh
Krishh

Reputation: 667

Change directory in terminal using python

I'm writing a simple script to change the present working directory to some other directory. The following script works okay until the program terminates, after which I'm back to my home directory.

#!/usr/bin/python

import os

if __name__ == '__main__':
    os.chdir("/home/name/projects/python")
    os.system("pwd")
    print 'dir changed'

Output is:

bash:~$ python chdir.py
/home/name/projects/python
dir changed
bash:~$ pwd
/home/name

I want the directory change to remain even after the program has exited. Any ideas how to do it?

Edit: What I really want to do is this: I use this directory frequently and instead of doing cd <path> every time I open the terminal, I just write ./progname and it changes the directory.

Upvotes: 18

Views: 32033

Answers (3)

spen.smith
spen.smith

Reputation: 587

In case someone would like to do this without python - this is most simply done with a .bash_profile file.

Steps:

  1. Type this into your .bash_profile. You can open this file with pico.
pico ~/.bash_profile
  1. Then create a shortcut (called an alias), you can do whatever phrase you want.
alias cdd="cd ~/frequent/my-directory"
  1. Then source your .bash_profile file.
source ~/.bash_profile

Now, you just run your aforementioned shortcut, and this switches your directory, with many less key strokes!

Macbook-Spen:~ spen$ cdd
Macbook-Spen:my-directory spen$ 

Sources:

Upvotes: 0

Yaron
Yaron

Reputation: 10450

If you want the directory change to remain even after the program has exited. You can end the python script with os.system("/bin/bash"), this will leave you in bash shell inside the new directory.

#!/usr/bin/python
import os
if __name__ == '__main__':
    os.chdir("/home/name/projects/python")
    os.system("pwd")
    os.system("/bin/bash")

For the need raised in your comment "I use this directory frequently and instead of doind cd <path> every time I open the terminal, I just write ./progname and it changes the directory"
I would suggest using bash alias which will change directory:

bash:~$ alias mycd='cd /home/name/projects/python'

and use this alias in bash shell in order to change the directory:

bash:~$ mycd

You can add this alias to your .bashrc - which will allow you to use this alias every time.

Upvotes: 19

Himanshu dua
Himanshu dua

Reputation: 2513

import os
os.system('cd /home/name/projects/python')

Upvotes: -1

Related Questions