Change directory in terminal using python

十年热恋 提交于 2019-11-28 00:30:07

问题


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.


回答1:


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.




回答2:


This answer is exactly the same as the accepted in that it solves the problem, which adds no value, but goes about it a little differently. I think this answer maybe adds value in explanation and alternate implementation. You can decide.

Okay, sorry for yelling.

You should just edit your .bash_profile file. It's really simple. Touch creates the file, and then open functionally opens it. In your terminal:

touch ~/.bash_profile; open ~/.bash_profile

This opens Text Edit. Create your shortcut like this, I put it at the end of my file:

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

Then run this to update your .bash_profile file. (Or close and reopen the terminal, whatever you like.)

source ~/.bash_profile

Now, you just run your aforementioned shortcut:

Macbook-Spen:~ spen$ cdd

And this switches your directory, with many less key strokes!

Macbook-Spen:my-directory spen$ 

Sources:

  • https://www.moncefbelyamani.com/create-aliases-in-bash-profile-to-assign-shortcuts-for-common-terminal-commands/

  • How do I edit $PATH (.bash_profile) on OSX?




回答3:


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


来源:https://stackoverflow.com/questions/35843054/change-directory-in-terminal-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!