Change directory in terminal using python

I am writing a simple script to change the current working directory to another directory. The following script works fine until the program exits, after which I will return 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:

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 exits. Any ideas how to do this?

Edit : I really want to do this: I often use this directory and instead of doing it cd <path>every time I open the terminal, I just write ./prognameand change the directory.

+5
source share
4 answers

, . python os.system("/bin/bash"), bash .

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

, : " doind cd <path> , , ./progname "
bash, :

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

bash, :

bash:~$ mycd

.bashrc .

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

, script . cd , , , .

bash script, source program.sh program.sh "", , , .

, , /bin/bash cd, , , bash Python. , .

, - . , bash.

0

, , , -. , , , . .

, .

.bash_profile. . , . :

touch ~/.bash_profile; open ~/.bash_profile

. , :

alias cdd="cd ~/frequent/my-directory"

, .bash_profile. ( , .)

source ~/.bash_profile

:

Macbook-Spen:~ spen$ cdd

And that switches your directory, with far fewer keystrokes!

Macbook-Spen:my-directory spen$ 

Sources:

0
source

Source: https://habr.com/ru/post/1656267/


All Articles